1

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?

2 Answers 2

3

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.

1

You can also specify multiple patterns with -e.

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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