How can I exclude one word with grep?
You can do it using -v
(for --invert-match
) option of grep as:
grep -v "unwanted_word" file | grep XXXXXXXX
grep -v "unwanted_word" file
will filter the lines that have the unwanted_word
and grep XXXXXXXX
will list only lines with pattern XXXXXXXX
.
EDIT:
From your comment it looks like you want to list all lines without the unwanted_word
. In that case all you need is:
grep -v 'unwanted_word' file
I understood the question as "How do I match a word but exclude another", for which one solution is two greps in series: First grep finding the wanted "word1", second grep excluding "word2":
grep "word1" | grep -v "word2"
In my case: I need to differentiate between "plot" and "#plot" which grep's "word" option won't do ("#" not being a alphanumerical).
Hope this helps.
If your grep
supports Perl regular expression with -P
option you can do (if bash; if tcsh you'll need to escape the !
):
grep -P '(?!.*unwanted_word)keyword' file
Demo:
$ cat file
foo1
foo2
foo3
foo4
bar
baz
Let us now list all foo
except foo3
$ grep -P '(?!.*foo3)foo' file
foo1
foo2
foo4
$
The right solution is to use grep -v "word" file
, with its awk
equivalent:
awk '!/word/' file
However, if you happen to have a more complex situation in which you want, say, XXX
to appear and YYY
not to appear, then awk
comes handy instead of piping several grep
s:
awk '/XXX/ && !/YYY/' file
# ^^^^^ ^^^^^^
# I want it |
# I don't want it
You can even say something more complex. For example: I want those lines containing either XXX
or YYY
, but not ZZZ
:
awk '(/XXX/ || /YYY/) && !/ZZZ/' file
etc.