如何在文件中搜索多行模式? [英] How can I search for a multiline pattern in a file?
问题描述
我需要找到包含特定字符串模式的所有文件。第一个解决方案是使用 管道输入 xargs grep :
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'
但是如果我需要找到跨越多行的模式,因为vanilla grep找不到多行模式。
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.
推荐答案
所以我发现了 pcregrep 代表 Perl Compatible Regular Expressions GREP
例如,您需要查找 _name 变量紧跟其后的' _description 'variable:
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'
提示:在您的模式中的换行符。根据您的平台,它可以是'\\\
',\r','\r\\\
',...
Tip: you need to include the line break character in your pattern. Depending on your platform, it could be '\n', \r', '\r\n', ...
这篇关于如何在文件中搜索多行模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!