Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter word between two patterns - Linux

Tags:

string

regex

sed

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

like image 302
Raj87 Avatar asked Jul 11 '26 23:07

Raj87


1 Answers

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
like image 153
tink Avatar answered Jul 14 '26 13:07

tink



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!