regex - Multiple exclusion patterns with grep

08
2014-07
  • Alex Reynolds

    I would like to select lines which do not match the specified pattern, where I have multiple patterns to exclude. As an example, I want to exclude lines which start with the keywords apple and banana:

    $ grep -v '^apple' foo.txt | grep -v '^banana' -
    

    I'm wondering if there's a way to do it with one expression or one call to grep. I have tried the following, but they don't seem to work as hoped:

    $ grep -v "^apple" -v "^banana" foo.txt
    $ grep -v "^(apple|banana)" foo.txt
    $ grep -v "(^apple)|(^banana)" foo.txt
    

    What is a correct way to exclude multiple patterns?

  • Answers
  • Kevin Fegan

    To specify "alternate" matches, you have to include the "E" switch like:

    $ grep -Ev "^(apple|banana)" foo.txt
    $ grep -Ev "(^apple)|(^banana)" foo.txt
    

    Either version above should work.

  • cpugeniusmv

    You can also specify multiple patterns with -e.

    grep -e '^apple' -e '^banana' -v foo.txt

    grep -e '^apple' -e '^banana' foo.txt


  • Related Question

    search - Searching Multiple Terms
  • nevets1219

    I know that grep -E 'termA|termB' files allows me to search multiple files for termA OR termB. What I would like to do instead is search for termA AND termB. They do not have to be on the same line as long as the two terms exists within the same file. Essentially a "search within result" feature.

    I know I can pipe the results of one grep into another but that seems slow when going over many files.

    grep -l "termA" * | xargs grep -l "termB" | xargs grep -E -H -n --color "termA|termB"
    

    Hopefully the above isn't the only way to do this.

    It would be extra nice if this could work on Windows (have cygwin) and Linux. I don't mind installing a tool to perform this task.


  • Related Answers
  • Ignacio Vazquez-Abrams

    You can use awk for this. Simply set a flag per match you're looking for, then check to see if all the flags have been set.