How to find patterns across multiple lines using grep?

后端 未结 26 1693
你的背包
你的背包 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:22

    Grep is not sufficient for this operation.

    pcregrep which is found in most of the modern Linux systems can be used as

    pcregrep -M  'abc.*(\n|.)*efg' test.txt
    

    where -M, --multiline allow patterns to match more than one line

    There is a newer pcre2grep also. Both are provided by the PCRE project.

    pcre2grep is available for Mac OS X via Mac Ports as part of port pcre2:

    % sudo port install pcre2 
    

    and via Homebrew as:

    % brew install pcre
    

    or for pcre2

    % brew install pcre2
    

    pcre2grep is also available on Linux (Ubuntu 18.04+)

    $ sudo apt install pcre2-utils # PCRE2
    $ sudo apt install pcregrep    # Older PCRE
    

提交回复
热议问题