sup
sup

Reputation: 734

Search with grep for two expressions at once

This is basic but I am unable to google it. Can I use on invokation of grep to do

grep expr1 | grep expr2

so that it prints lines including both expr1 and expr2?

Upvotes: 39

Views: 48387

Answers (4)

rounin
rounin

Reputation: 1361

You can provide several expressions to search for with several -e flags. See also this post.

i.e.

grep -e expr1 -e expr2

Upvotes: 49

user3728877
user3728877

Reputation: 11

Actually your own suggestion is nearly correct if you want to get the lines that contain both expressions. Use:

grep expr1 somefile | grep expr2

Upvotes: 1

twm
twm

Reputation: 1458

Try this:

grep 'expr1.*expr2\|expr2.*expr1'

That's a little more complicated than it needs to be if you know that "expr2" will always come after "expr1". In that case, you could simplify it to:

grep 'expr1.*expr2'

Upvotes: 33

NPE
NPE

Reputation: 500357

What you have should work.

The following is an alternative way to achieve the same effect:

grep -E 'expr1.*expr2|expr2.*expr1'

Upvotes: 3

Related Questions