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
Share:
25,393
Ocasta Eshu
Author by

Ocasta Eshu

BA: English, Economics Minor: Computer Science Case Western Reserve University - 2012

Updated on September 18, 2022

Comments

  • Ocasta Eshu
    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
    Ocasta Eshu almost 12 years
    I 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
    speakr over 11 years
    You can also use egrep (an alias for grep -E) instead of grep.