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

时间:2014-02-10 21:25:46

标签: regex linux sed

这是一个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

我还没弄明白如何获得多线匹配。

3 个答案:

答案 0 :(得分:2)

这条线适合您的需要:

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

你可以使正则表达式更加严格,就像使用^ and $一样,但你知道如何处理它。

答案 1 :(得分:2)

如果您愿意,

仍然可以在sed中完成。

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

results1d
results1e
results1f

答案 2 :(得分:1)

这可能适合你(GNU):

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