How to find patterns across multiple lines using grep?

后端 未结 26 1713
你的背包
你的背包 2020-11-22 04:14

I want to find files that have \"abc\" AND \"efg\" in that order, and those two strings are on different lines in that file. Eg: a file with content:

blah bl         


        
26条回答
  •  遇见更好的自我
    2020-11-22 04:38

    Here is a solution inspired by this answer:

    • if 'abc' and 'efg' can be on the same line:

        grep -zl 'abc.*efg' 
      
    • if 'abc' and 'efg' must be on different lines:

        grep -Pzl '(?s)abc.*\n.*efg' 
      

    Params:

    • -P Use perl compatible regular expressions (PCRE).

    • -z Treat the input as a set of lines, each terminated by a zero byte instead of a newline. i.e. grep treats the input as a one big line.

    • -l list matching filenames only.

    • (?s) activate PCRE_DOTALL, which means that '.' finds any character or newline.

提交回复
热议问题