【shell】文本匹配问题

原文本通过TITLE分段
TITLE1
xxx
yyy
TITLE2
xxx
yyy
hello
zzz
hello
TITLE3
xxx
hello

类似于这样的,hello可能有多个,需要打印出含hello对应的TITLE段落,如(TITLE1不含hello,不打印):
TITLE2
hello
hello
TITLE3
hello


我的解题思路是首先用grep找出所有包括TITLE和hello的行,然后通过sed的N把下一行(最后一行除外)读入模式空间,如果包含 /hello/,那么用P打印当前模式空间,然后D删除打印完的内容。

[root]$ cat file | grep -E 'TITLE|hello' | sed -n '{$!N;/hello/{P};D}'
TITLE2
hello
hello
TITLE3
hello
原文地址:https://www.cnblogs.com/seyjs/p/5591351.html