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

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:

find . -iname '*.py' | xargs grep -e 'YOUR_PATTERN'

But if I need to find patterns that spans on more than one line, I'm stuck because vanilla grep can't find multiline patterns.


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', 'rn', ...


你为什么不去awk:

awk '/Start pattern/,/End pattern/' filename

Here is the example using GNU grep :

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

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

链接地址: http://www.djcxy.com/p/47240.html

上一篇: 包含多种文件类型的选项?

下一篇: 我如何在文件中搜索多行模式?