Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How do I grep for multiple patterns with pattern having a pipe character?

I want to find all lines in several files that match one of two patterns. I tried to find the patterns I'm looking for by typing

grep (foo|bar) *.txt


but the shell interprets the | as a pipe and complains when bar isn't an executable.

How can I grep for multiple patterns in the same set of files?
by

2 Answers

rahul07

egrep "foo|bar" .txt

or

grep "foo\|bar" *.txt
grep -E "foo|bar"
.txt

selectively citing the man page of gnu-grep:

-E, --extended-regexp
Interpret PATTERN as an extended regular expression (ERE, see below). (-E is specified by POSIX.)

Matching Control
-e PATTERN, --regexp=PATTERN
Use PATTERN as the pattern. This can be used to specify multiple search patterns, or to protect a pattern
beginning with a hyphen (-). (-e is specified by POSIX.)

(...)

grep understands two different versions of regular expression syntax: “basic” and “extended.” In GNU grep, there
is no difference in available functionality using either syntax. In other implementations, basic regular
expressions are less powerful. The following description applies to extended regular expressions; differences for
basic regular expressions are summarized afterwards.

In the beginning I didn't read further, so I didn't recognize the subtle differences:

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

I always used egrep and needlessly parens, because I learned from examples. Now I learned something new. :)
pankajshivnani123
Firstly, you need to use quotes for special characters. Second, even so, grep will not understand alternation directly; you would need to use egrep, or (with GNU grep only) grep -E.

egrep 'foo|bar' *.txt
(The parentheses are unnecessary unless the alternation is part of a larger regex.)

Login / Signup to Answer the Question.