How to Match Multiple Strings with grep
If you need to match a string in a file, then grep is your friend.
An example of using grep
Let’s take a file called somefile.txt
this
is
a
test
that
looks
for
something
We can look for the string something in this file using grep:
cat somefile.txt | grep something
# something
But what if we want to look for both something and this?
An example of using multiple greps
It’s pretty easy, we just pass the -E flag, which is short for --extended-regexp, and separate our strings with a pipe |.
cat somefile.txt| grep -E "something|this"
# this
# something
All the ways to use grep multiple patterns
Multiples:
grep 'word1\|word2\|word3' /path/to/file
Search all text files:
grep 'word*' *.txt
Search all python files for wordA and wordB:
grep 'wordA*'\''wordB' *.py
grep -E 'word1|word2' *.doc
grep -e string1 -e string2 *.pl
egrep "word1|word2" *.c
Show all the lines that do not match given pattern/words/strings:
grep -v 'bar\|foo' /dir1/dir2/file1
egrep -v 'pattern1|pattern2' /path/to/file