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

后端 未结 11 992
陌清茗
陌清茗 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:57

    So I discovered pcregrep which stands for Perl Compatible Regular Expressions GREP.

    For example, you need to find files where the '_name' variable is immediatelly followed by the '_description' variable:

    find . -iname '*.py' | xargs pcregrep -M '_name.*\n.*_description'
    

    Tip: you need to include the line break character in your pattern. Depending on your platform, it could be '\n', \r', '\r\n', ...

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

    grep -P also uses libpcre, but is much more widely installed. To find a complete title section of an html document, even if it spans multiple lines, you can use this:

    grep -P '(?s)<title>.*</title>' example.html
    

    Since the PCRE project implements to the perl standard, use the perl documentation for reference:

    • http://perldoc.perl.org/perlre.html#Modifiers
    • http://perldoc.perl.org/perlre.html#Extended-Patterns
    0 讨论(0)
  • 2020-11-22 15:57

    Using ex/vi editor and globstar option (syntax similar to awk and sed):

    ex +"/string1/,/string3/p" -R -scq! file.txt
    

    where aaa is your starting point, and bbb is your ending text.

    To search recursively, try:

    ex +"/aaa/,/bbb/p" -scq! **/*.py
    

    Note: To enable ** syntax, run shopt -s globstar (Bash 4 or zsh).

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

    @Marcin: awk example non-greedy:

    awk '{if ($0 ~ /Start pattern/) {triggered=1;}if (triggered) {print; if ($0 ~ /End pattern/) { exit;}}}' filename
    
    0 讨论(0)
  • 2020-11-22 16:02

    This answer might be useful:

    Regex (grep) for multi-line search needed

    To find recursively you can use flags -R (recursive) and --include (GLOB pattern). See:

    Use grep --exclude/--include syntax to not grep through certain files

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