Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there a simpler way to do this? grep -v foo file | grep -v bar

There're probably very elegant ways to do it with egrep, but how to go with plain old grep?

EDIT: grep -v 'foo\|bar' file seems to work only with GNU grep. I'm on Solaris. Any solution for that?

share|improve this question
Strange question because in the first example you are doing AND match, and in the second you are doing OR match. The outcome will be the same only in very specific conditions. – greenoldman Nov 10 '12 at 7:40
No not really. In the second example, the -v flag is a negation. not(A or B) == not(A) and not(B) – rahmu Nov 10 '12 at 10:02
up vote 8 down vote accepted

You can have multiple tests in a single grep command by passing each expression with a -e argument instead of as the first non-option argument as you normally see:

$ grep -v -e foo -e bar file

That says the same thing your command does: print lines from file that contain neither "foo" nor "bar".

Keep in mind that removing -v completely inverts this; it changes the logical operation, too! You get all lines that contain "foo" or "bar".

share|improve this answer

grep -Ev 'word1|word2' should work just fine

share|improve this answer
As an alternative you can use egrep and drop the backslash for the pipe character: egrep -v 'word1|word2 – OldTimer Aug 26 '11 at 10:46
Turns out this does not work with the Solaris grep. I installed the GNU grep and worked perfectly. I'm going to edit my question to make it Solaris specific. – rahmu Aug 26 '11 at 10:52
@rahmu \| is a GNU grep extension, but you can achieve the same thing in a portable way with -E and the | operator. – Gilles Aug 26 '11 at 22:42

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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