Search code examples
shellunixsedcriteriaconditional-statements

Sed with multiple criteria


I have 3 sed commands:

sed -n 's/.*domain=\([^&]*\).*sdk_ver=\([^&]*\).*/\1 \2/p' inputfile > outputfile
sed -n 's/.*sdk_version=\([^&]*\).*domain=\([^&]*\).*/\2 \1/p'  inputfile > outputfile
sed -n 's/.*domain=\([^&]*\).*sdk_version=\([^&]*\).*/\1 \2/p' inputfile > outputfile

Each command has a criterion in it. I just want to put 3 commands into 1 command, to get a single output file which includes all the results as a union of the three criteria.


Solution

  • Use Multiple Sed Expressions

    You can place multiple sed expressions in a script separated by newlines, or as multiple expressions delimited by the -e option. For example:

    sed -n -e 's/.*domain=\([^&]*\).*sdk_ver=\([^&]*\).*/\1 \2/'      \
           -e 's/.*sdk_version=\([^&]*\).*domain=\([^&]*\).*/\2 \1/'  \
           -e 's/.*domain=\([^&]*\).*sdk_version=\([^&]*\).*/\1 \2/p' \
           inputfile > outputfile
    

    In this example, sed will run the expressions sequentially on each input line, and only print the pattern space after the final expression in the sequence is processed. There are certainly other ways to do this, but given your example this seems the most appropriate.