Tuesday, May 27, 2008

Use the OR operator in grep to search for words and phrases

grep is a very powerful command-line search program in the Linux world. In this article, I will cover how to use OR in the grep command to search for words and phrases in a text file.

Suppose you want to find all occurrences of the words "apples" and "oranges" in the text file named fruits.txt.

$ cat fruits.txt
yellow bananas
green apples
red oranges
red apples


$ grep 'apples\|oranges' fruits.txt
green apples
red oranges
red apples


Note that you must use the backslash \ to escape the OR operator (|).

Using the OR operator, you can also search for phrases like "green apples" and "red oranges". You must escape all spaces in a phrase in addition to the OR operator.
$ grep 'green\ apples\|red\ oranges' fruits.txt
green apples
red oranges


You can get away with not escaping the spaces or the | operator if you use the extended regular expression notation.
$ grep -E 'green apples|red oranges' fruits.txt
green apples
red oranges


egrep is a variant of grep that is equivalent to grep -E.
$ egrep 'green apples|red oranges' fruits.txt
green apples
red oranges


P.S. Additional grep articles from this blog:


8 comments:

CKing27@mac.com said...

Thanks. Helpful.

Unknown said...

this is very important.

The awk and sed alternatives,

awk '/apples|oranges/' file.out

sed -e '/apples/b' -e '/oranges/b' -e d file.out


http://unstableme.blogspot.com/2008/03/or-and-and-in-grep.html

Anonymous said...

Thank you man!!! its very very useful!! I've been looking for this!!!

izeye said...

Thank you. This helped me :-)

Anonymous said...

Thanks! it helped me.

Anonymous said...

good info....

Anonymous said...

Thank you for posting that, very useful!

Unknown said...

Hi, I love the simple solution, no need for sed or awk. Thank a lot.