Regex for "or" of multiple words in grep
[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?
Solution 1:
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