简体   繁体   中英

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

Here's a commands.txt file:

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

Here's what I have so far:

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

And the output is

cmd1
cmd1

What I want the output to be is

results1d
results1e
results1f

I haven't figured out how to get multiline matches.

this line works for your needs:

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

you can make the regex more strict, like with ^ and $ , but you got my idea how to handle it.

still can be done in sed, if you prefer.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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