Mou*_*Dog 2 regular-expression
我有一个程序可以打印出块中的数据。每个块由空行分隔。
我想丢弃大多数块,只保留那些包含匹配正则表达式的块。
我当然可以用脚本语言或程序来完成,但这似乎相当粗糙。有没有更好的方法来做到这一点?
Sté*_*las 11
awk
并perl
有专门为此设计的特殊模式。称为段落模式。在这种模式下,记录是段落,即它们由空行序列分隔。
对于awk
,它设置RS
为空字符串:
awk -v RS= -v ORS='\n\n' '/regexp/'
Run Code Online (Sandbox Code Playgroud)
与perl
,它与-00
。
perl -00 -ne 'print if /regexp/'
Run Code Online (Sandbox Code Playgroud)
awk
通过将记录分隔符设置为双换行符,然后在记录中进行正则表达式匹配,通常可以在 中轻松完成此类操作。例如,如果我有
block #1
this block doesnt' contain
anything I want to keep
here's a block
with some important stuff
here's another
block of stuff
and another
Run Code Online (Sandbox Code Playgroud)
然后
$ awk -vRS="\n\n" '/important/ {print}' blocktext.txt
here's a block
with some important stuff
Run Code Online (Sandbox Code Playgroud)
如果你提供一个例子,肯定会更容易回答。