If you wish to exclude lines containing a specified pattern when using the grep command on a Unix, Linux, or OS X system, you can do so using the
-v, --invert-match Invert the sense of matching, to select non-matching lines. (-v is specified by POSIX.)
E.g., suppose I have a file
names.txt containing the following
$ cat names.txt John Smith Paul McCartney Bob Jones Allen Smith Greg Smith Bob Smith Carl Smith John Doe
If I want to view all lines except for those containing "Allen", I can
grep -v "Allen" names.txt. But what if I want to exclude
more than one pattern, e.g. any line containing "Allen" or "Bob". I could
pipe the output of one grep command to another grep command with
grep -v "Allen" names.txt | grep -v "Bob". Or you can perform
a logical disjunction using the
character, i.e., "
|", aka a "vertical bar".
$ grep -v "Allen\|Bob" names.txt John Smith Paul McCartney Greg Smith Carl Smith John Doe $
In the above example, I am instructing grep to ignore any lines containing either Allen or Bob in the line. Because the pipe character has another meaning to the Bash shell, i.e., it is used by the shell to "pipe" the output of one command to another with the output of the first command becoming the input of the second, its meaning must be "escaped" to be processed by grep as a logical disjunction symbol. That is done by preceding the character with a backslash, which is an escape character.