regexstringsed

How to filter word between two patterns - Linux


I would like to filter word between two patterns. In this case, between CN= and a comma (,)

Input:

Subject : "O=This is a test,CN=abc.def.com,L=North,ST=Arizona,C=CA"

Expected Output:

abc.def.com

Tried below but it isn't yielding expected results.

sed -n "/CN=/,/,/p" test.txt


Solution

  • The range notation works for patterns on separate lines. This should work for you:

    echo 'Subject : "O=This is a test,CN=abc.def.com,L=North,ST=Arizona,C=CA"' | sed -e 's/^.*CN=//' -e 's/,.*$//'
    abc.def.com
    

    Or with awk:

    echo 'Subject : "O=This is a test,CN=abc.def.com,L=North,ST=Arizona,C=CA"' | awk 'BEGIN{RS=","}/^CN=/{sub(/CN=/,"");print}'
    abc.def.com