Differences between revisions 2 and 3
Revision 2 as of 2007-05-03 13:11:27
Size: 933
Editor: GreyCat
Comment: fill it in a bit more
Revision 3 as of 2007-05-22 20:08:32
Size: 1006
Editor: JeremyBaron
Comment: added grep -e 'foo' -e 'bar'
Deletions are marked like this. Additions are marked like this.
Line 28: Line 28:

# This is another option, some people prefer:
grep -e 'foo' -e 'bar'

Anchor(faq79)

How can I grep for lines containing foo AND bar, foo OR bar?

The easiest way to match both foo AND bar is to use two grep commands:

grep foo | grep bar

It can also be done with one egrep, although (as you can probably guess) this doesn't really scale well to more than two patterns:

egrep 'foo.*bar|bar.*foo'

If you prefer, you can achieve this in one sed or awk statement. (The awk example is probably the most scalable.)

sed -n '/foo/{/bar/p}'
awk '/foo/ && /bar/'

To match lines containing foo OR bar, egrep is the natural choice, but it can also be done with sed, awk, etc.

egrep 'foo|bar'
# some people prefer grep -E 'foo|bar'

# This is another option, some people prefer:
grep -e 'foo' -e 'bar'

egrep is the oldest and most portable form of the grep command using Extended Regular Expressions (EREs). -E is a POSIX-required switch.

BashFAQ/079 (last edited 2023-01-26 22:54:33 by emanuele6)