Regex for "or" of multiple words in grep
25,393
grep uses basic regular expressions (BRE) by default. From the man page:
Basic vs Extended Regular Expressions: In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, +, {, \|, (, and ).
So you either have to escape the |
:
grep "foo\|bar" filename
or turn on extended regular expressions:
grep -E "foo|bar" filename
Author by
Ocasta Eshu
BA: English, Economics Minor: Computer Science Case Western Reserve University - 2012
Updated on September 18, 2022Comments
-
Ocasta Eshu over 1 year
[Computer]$ grep "foo|bar" filename
I understand the above command should return each line in filename where there exits "foo" or "bar". The man pages confirms | as the Regex or symbol and the code works for "foo" and "bar" independently. What am I missing?
-
Ocasta Eshu almost 12 yearsI saw that in the man page and misunderstood. I thought it meant that \| would make it look for the complete expression "foo|bar" as opposed to the individual expressions. Thanks for the fast response!
-
speakr over 11 yearsYou can also use
egrep
(an alias forgrep -E
) instead ofgrep
.