Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get sed to match a pattern with multiple exceptions?

Consider the following config file

; My Config
;

[CITY]
URL='my.city.com'
ID='1234'
PID='1'

[SITE]
URL='my.site.com'
ID='2345'
PID='2'

[UNIT]
URL='my.unit.com'
ID='3456'
PID='3'

[BOB]
URL='my.bob.com'
ID='123456'
PID='15'

. . .

My goal is to strip all the fields past the first three. The first three have fixed names, the others are variable. I came close with:

sed -e '/.*\[[^DUC].*\]/Q' test.conf

Which gave me what I wanted:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

; My Config
;

[CITY]
URL='my.city.com'
ID='1234'
PID='1'

[SITE]
URL='my.site.com'
ID='2345'
PID='2'

[UNIT]
URL='my.unit.com'
ID='3456'
PID='3'

But it fails if the first name past these three starts with ‘C’, ‘S’ or ‘U’. What I’m really looking for is a way to do a negative comparison against the three strings "CITY", "SITE" and "UNIT". Is there a way to do that with sed, or am I barking up the wrong tree?

>Solution :

Perl to the rescue!

perl -pe 'exit if /\[(?!CITY|SITE|UNIT).*\]/' test.conf
  • -p reads the input line by line and prints each line after processing;
  • (?!pattern) is a negative look-ahead assertion, i.e. it says "pattern doesn’t follow", but consumes no characters. BOB in this example is consumed by the .* because the negative look-ahead succeeds.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading