繁体   English   中英

如何使用sed / regex查找最后的多行匹配?

[英]How do I use sed/regex to find the last multiline match?

这是一个commands.txt文件:

START - 'cmd1'
results1a
results1b
results1c
END - 'cmd1'
START - 'cmd2'
results2a
results2b
END - 'cmd1'
START - 'cmd1'
results1d
results1e
results1f
END - 'cmd1'

这是我到目前为止的内容:

cat commands.txt | sed -n 's/^START - '"'"'(cmd1)'"'"'$/\1/p'

输出是

cmd1
cmd1

我想要的输出是

results1d
results1e
results1f

我还没有弄清楚如何获得多行比赛。

这条线适合您的需求:

awk "NR==FNR{if(/^START - 'cmd1'/)p=NR;next}FNR>p{if(/^END/)exit;print}" file file

您可以使regex更加严格,例如使用^ and $ ,但是您知道了如何处理它。

如果愿意,仍然可以在sed中完成。

sed -r ':a;$!{N;ba};s/.*START[^\\\n]+\n(.*)\nEND.*/\1/' file

results1d
results1e
results1f

这可能对您有用(GNU):

sed '/START/h;//,/END/{//!H};$!d;x;s/[^\n]*\n//' file

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM