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

后端 未结 11 1170
陌清茗
陌清茗 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', ...

提交回复
热议问题