Search code examples
regexlinuxstringgrep

Match two strings in one line with grep


I am trying to use grep to match lines that contain two different strings. I have tried the following but this matches lines that contain either string1 or string2 which not what I want.

grep 'string1\|string2' filename

So how do I match with grep only the lines that contain both strings?


Solution

  • You can use

    grep 'string1' filename | grep 'string2'
    

    This searches for string1 followed by string 2 on the same line, or string2 followed by string1 on the same line; it does not answer the question:

    grep 'string1.*string2\|string2.*string1' filename