1275

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

grep '[^foo]'
1
  • 13
    [^error_log] would never ever work anyway, [] are char classes, regexp 's in general are not good at negative patterns (unless the engine implements negative lookaheads).
    – Jaap
    Nov 9, 2011 at 15:49

3 Answers 3

2243

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

13
  • 177
    Worth mentioning that for multiple (negative) matches -e option can be used: grep -v -e 'negphrase1' -e 'negphrase2' Jun 18, 2014 at 9:30
  • 44
    Similar to the comment from @Babken-Vardanyan Also - able to use pipes to join multiple matches e.g. grep -v 'negphrase1|negphrase2|negphrase3' Aug 5, 2015 at 6:56
  • 24
    Last comment is NOT the same as it will search for things that don't match both rather than either. ie If it matches one but not the other its still printed. Try it both ways with non-similar strings Dec 13, 2015 at 6:52
  • 15
    @EvanLanglois - forcing grep to interpret the pattern as an extended regular expression using -E works, i.e. grep -vE 'negphrase1|negphrase2|negphrase3'
    – Zlemini
    Nov 17, 2016 at 18:57
  • 2
    @OlleHärstedt, I think I misunderstood your scenario in my previous comment, the following may be what you're looking for grep "" /dev/null * | grep foo | grep -v bar | cut -d: -f1 | sort -u (why the first grep?, there's always a way :))
    – Motti
    Oct 25, 2017 at 7:18
205

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.

3
  • 8
    That's actually quite cool. You don't even have to learn the complete awk language in order to group regexp with logical operators. Thanks for this answer!
    – Peter T.
    Sep 17, 2018 at 14:59
  • 4
    The OP specifically asks for grep. Why is this upvoted? Feb 9, 2022 at 9:33
  • It's possible that the OP wasn't aware of awk capabilities and providing an alternate solution that provides the same result is helpful.
    – Ed S
    Mar 17 at 17:38
22

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
1

Not the answer you're looking for? Browse other questions tagged or ask your own question.