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:
Thanks. Helpful.
ReplyDeletethis is very important.
ReplyDeleteThe 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
Thank you man!!! its very very useful!! I've been looking for this!!!
ReplyDeleteThank you. This helped me :-)
ReplyDeleteThanks! it helped me.
ReplyDeletegood info....
ReplyDeleteThank you for posting that, very useful!
ReplyDeleteHi, I love the simple solution, no need for sed or awk. Thank a lot.
ReplyDelete