jerrygarciuh
jerrygarciuh

Reputation: 21988

Negative matching using grep (match lines that do not contain foo)

How do I match all lines not matching a particular pattern using grep? I tried this:

grep '[^foo]'

Upvotes: 1364

Views: 1357282

Answers (3)

Papa Smurf
Papa Smurf

Reputation: 385

In your case, you presumably don't want to use grep, but add instead a negative clause to the find command, e.g.

find /home/baumerf/public_html/ -mmin -60 -not -name error_log

If you want to include wildcards in the name, you'll have to escape them, e.g. to exclude files with suffix .log:

find /home/baumerf/public_html/ -mmin -60 -not -name \*.log

Upvotes: 23

fedorqui
fedorqui

Reputation: 289545

You can also use awk for these purposes, since it allows you to perform more complex checks in a clearer way:

Lines not containing foo:

awk '!/foo/'

Lines containing neither foo nor bar:

awk '!/foo/ && !/bar/'

Lines containing neither foo nor bar which contain either foo2 or bar2:

awk '!/foo/ && !/bar/ && (/foo2/ || /bar2/)'

And so on.

Upvotes: 220

Motti
Motti

Reputation: 114695

grep -v is your friend:

grep --help | grep invert  

-v, --invert-match select non-matching lines

Also check out the related -L (the complement of -l).

-L, --files-without-match only print FILE names containing no match

Upvotes: 2403

Related Questions