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?

1 Answer

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
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like