37

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?

sup
  • 680
  • 1
  • 6
  • 17
  • Possible duplicate of [How to use grep to match string1 AND string2?](https://stackoverflow.com/q/4487328/608639) – jww Mar 13 '19 at 04:45

4 Answers4

46

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

i.e.

grep -e expr1 -e expr2

Ralf Stubner
  • 26,263
  • 3
  • 40
  • 75
rounin
  • 1,310
  • 10
  • 12
  • @sup: in GNU grep 2.16 the suggested command line searches both expressions – fred Mar 05 '18 at 13:12
  • 5
    I am running GNU GREP 2.25 and running `grep --version |grep -e is -e software` does not seem to search for lines containing both exrpresions, but it searches for lines containing either expresion. – sup Mar 05 '18 at 16:46
33

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'

twm
  • 1,448
  • 11
  • 19
  • Rather than have a lot of identical questions - above worked for me except I did: ` sudo grep -E -rnw '/var/log/' -e 'Out of memory.*Jan 17|Jan 17.*Out of memory'` - without the backslash. Linux Mint 18.3, GNU bash 4.3.48 – nate Jan 17 '18 at 22:50
3

What you have should work.

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

grep -E 'expr1.*expr2|expr2.*expr1'
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • I know it works:-). I was just tired of invoking grep two times all over. But it seems it is quicker to just write grep twice then to type this in. Unfortunately, I often do not know the order of expressions. I was hoping for something like `grep (expr1ANDexpr2)` :-). By the way, is this even faster in a sript than calling grep twice? – sup Feb 27 '13 at 16:02
1

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

grep expr1 somefile | grep expr2