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

Advertisements

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:

; 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.

Leave a ReplyCancel reply