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:
Thanks. Helpful.
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
Thank you man!!! its very very useful!! I've been looking for this!!!
Thank you. This helped me :-)
Thanks! it helped me.
good info....
Thank you for posting that, very useful!
Hi, I love the simple solution, no need for sed or awk. Thank a lot.
Post a Comment