Wednesday, May 4, 2016

How to Search for Multiple String Patterns Using GNU grep

Say you want to search for string patterns cat and dog within a text file. First, let's create a sample text file
$ echo "Hello cat" > test
$ echo "Bye dog" >> test
$ echo "Hello cat and bye dog" >> test
$ echo "Bye dog and hello cat" >> test
$ echo "Happy hacking" >> test

So, the test file has 4 lines of strings.
$ cat test
Hello cat
Bye dog
Hello cat and bye dog
Happy hacking

Now, let's first find the line containing the string cat
$ grep 'cat' test
Hello cat
Hello cat and bye dog

By the way, if you are not seeing the colored output, then you probably want to alias grep with --color-auto option in the ~/.bashrc file (Linux) or ~/.bash_profile (Mac OS X) file
$ echo "alias grep='grep --color-auto'" >> ~/.bashrc

Now, in order to find lines that contains either cat OR dog, we could run any of the following
$ grep 'cat\|dog' test
$ grep -e 'cat' -e 'dog' test
$ grep -E 'cat|dog' test
Hello cat
Bye dog
Hello cat and bye dog

What if you want to find lines that contain both cat AND dog? This will do:
$ grep 'cat' test | grep 'dog' test
Hello cat and bye dog

But you may notice that only the string dog is highlighted. To highlight both words, we could simply pipe an additional grep statement among the three commands above that search for cat OR dog:
$ grep 'cat' test | grep 'dog' test | grep -e 'cat' -e 'dog'
Hello cat and bye dog

2 comments: