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
Code language: plaintext (plaintext)

We can look for the string something in this file using grep:

cat somefile.txt | grep something # something
Code language: Bash (bash)

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
Code language: Bash (bash)

All the ways to use grep multiple patterns


grep 'word1\|word2\|word3' /path/to/file
Code language: Bash (bash)

Search all text files:

grep 'word*' *.txt
Code language: Bash (bash)

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
Code language: Bash (bash)

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
Code language: Bash (bash)
Notify of
Inline Feedbacks
View all comments