如何在文件中搜索多行模式?

时间:2020-03-06 14:55:07  来源:igfitidea点击:

我需要找到所有包含特定字符串模式的文件。我想到的第一个解决方案是使用通过xargs grep传递的find:

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

但是,如果我需要找到跨越多条线的模式,则会陷入困境,因为vanilla grep无法找到多线模式。

解决方案

因此,我发现pcregrep代表Perl兼容正则表达式GREP。

例如,我们需要找到在文件名后紧跟着" _name"变量的文件:

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

提示:我们需要在模式中包括换行符。根据平台,它可能是'\ n',\ r','\ r \ n',...

这是使用GNUgrep的示例:

grep -Pzo '_name.*\n.*_description'
-z/--null-data Treat  input and output data as sequences of lines.

这是一个更有用的示例:

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

即使它跨越多行,它也会在html文件中搜索标题标签。

你为什么不去求学:

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