Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep/awk: exclude words conditionally

Tags:

regex

grep

awk

I have data formatted like this:

a cat
a dog
brown cat
brown dog
brown cow
brown sheep
brown fish

I want to filter out all of the lines starting with "brown", except brown dog. Is there an easy way to do this with grep or awk? I tried to use the carat negation like so:

grep -v "brown ^\(dog\)" corpus.txt

... but that didn't work. Any ideas would be greatly appreciated.

Eventually I want the output to be like this:

a cat
a dog
brown dog
like image 550
tedx Avatar asked Aug 28 '26 01:08

tedx


1 Answers

Using awk:

awk '/^brown dog/ || !/^brown/' file
a cat
a dog
brown dog

Just as an academic exercise here is a grep command without experimental PCRE option:

grep -vE '^brown($|[^ ]| ([^d]|$)| d([^o]|$)| do([^g]|$))' file
like image 184
anubhava Avatar answered Aug 29 '26 18:08

anubhava



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!