9

Here's an example of a grep command line I've tried:

grep '(565172|565173|565175)' /var/log/cups/error_log

It doesn't produce any output, even though all 3 values are in the file multiple times.

I tried escaping the bars, and that improved things somewhat - the middle value was detected but not the first or last.

grep '(565172\|565173\|565175)' /var/log/cups/error_log

I also tried double escapes and went back to getting no results.

grep '(565172\\|565173\\|565175)' /var/log/cups/error_log

What am I doing wrong? Thanks.

2 Answers 2

17

What you are running into is the difference between basic and extended regular expressions. From grep's manual page:

In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, +, {, \|, (, and ).

Thus, you can do one of the following:

 grep '\(565172\|565173\|565175\)' /var/log/cups/error_log

or

grep -E '(565172|565173|565175)' /var/log/cups/error_log

The -E flag turns on "Extended" regular expressions. GNU grep also supports perl-compatible regular expressions.

4
  • Got distracted when writing my answer. Seems that Adam has beaten me to the punch.
    – Steven D
    Sep 15, 2010 at 19:07
  • 4
    But you added to the explanation - the reason I couldn't make it work is that I was escaping only the bar and not the parens. Sep 15, 2010 at 19:38
  • 1
    I didn't know that you can escape these special characters once more to get the same result, so +1 for you! Sep 15, 2010 at 20:28
  • 1
    The above is the most civilized set of exchanges I have ever seen in SO/SE. Dec 27, 2017 at 15:39
14

The syntax you are trying to use belongs to extended regular expressions, so the answer is very simple, either use egrep or include the -E flag.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .