【发布时间】:2017-06-06 20:38:14
【问题描述】:
我希望在 shell 脚本中匹配多行的模式。我的输入是:
START <some data including white spaces>
<some data including white spaces, can span across multiple lines, number of lines are variable>
ID: n1 <some data including white spaces>
<some data including white spaces, can span across multiple lines, number of lines are variable>
END
START <some data including white spaces>
<some data including white spaces, can span across multiple lines, number of lines are variable>
ID: n2 <some data including white spaces>
<some data including white spaces, can span across multiple lines, number of lines are variable>
END
我正在尝试使用正则表达式仅针对特定 ID(例如 n1 或 n2)显示输出。我尝试了START(.|\n)*ID: n1(.|\n)*END regex,但它也获取了 ID: n2 的数据。我应该对正则表达式进行哪些更改才能仅获取特定 ID 的数据?
我使用cat inputfile | grep 'pattern' > outputfile 作为命令。
每个块中的行数以及START 和ID: n1、ID: n1 和END 之间的行数可以是可变的,因此使用head/tail 不是一个可行的选项。另外,当 ID 匹配时,我想打印从 START 到 END 的整个块。
编辑:我尝试使用Online Regex Creator,它可以成功匹配正则表达式
START[\s\S][^END]*ID: n1[\s\S][^END]*END
在我的输入文件上。
【问题讨论】:
-
Perl 可以接受吗?在 Perl 中很容易...
标签: regex shell scripting grep