How can I search for a multiline pattern in a file?

后端 未结 11 991
陌清茗
陌清茗 2020-11-22 14:59

I needed to find all the files that contained a specific string pattern. The first solution that comes to mind is using find piped with xargs grep:

相关标签:
11条回答
  • 2020-11-22 15:38

    Why don't you go for awk:

    awk '/Start pattern/,/End pattern/' filename
    
    0 讨论(0)
  • 2020-11-22 15:38

    Here is a more useful example:

    pcregrep -Mi "<title>(.*\n){0,5}</title>" afile.html
    

    It searches the title tag in a html file even if it spans up to 5 lines.

    Here is an example of unlimited lines:

    pcregrep -Mi "(?s)<title>.*</title>" example.html 
    
    0 讨论(0)
  • 2020-11-22 15:40

    With silver searcher:

    ag 'abc.*(\n|.)*efg'
    

    Speed optimizations of silver searcher could possibly shine here.

    0 讨论(0)
  • 2020-11-22 15:46

    You can use the grep alternative sift here (disclaimer: I am the author).

    It support multiline matching and limiting the search to specific file types out of the box:

    sift -m --files '*.py' 'YOUR_PATTERN'

    (search all *.py files for the specified multiline regex pattern)

    It is available for all major operating systems. Take a look at the samples page to see how it can be used to to extract multiline values from an XML file.

    0 讨论(0)
  • 2020-11-22 15:48
    perl -ne 'print if (/begin pattern/../end pattern/)' filename
    
    0 讨论(0)
  • 2020-11-22 15:56

    Here is the example using GNU grep:

    grep -Pzo '_name.*\n.*_description'
    

    -z/--null-data Treat input and output data as sequences of lines.

    See also here

    0 讨论(0)
提交回复
热议问题