使用 sed 查找两个模式之间的线 [英] find lines between two patterns using sed

查看:43
本文介绍了使用 sed 查找两个模式之间的线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 text.txt 中有如下几行:

I have the lines in text.txt as below:

blah blah..
blah abc blah..
blah abc blah
blah blah..
blah blah..
blah blah..
blah efg blah blah
blah blah..
blah abc blah
blah abc blah
blah abc blah
blah abc blah
blah abc blah
blah blah..
blah efg blah blah
blah blah..
blah blah..

我想在efg"和efg"之前输出最后一次出现的abc"之间的行,对于上面的例子,我想输出:

I want to output the lines between each last occurrence of "abc" before "efg" and "efg", for the above example, I want to output:

blah abc blah
blah blah..
blah blah..
blah blah..
blah efg blah blah
blah abc blah
blah blah..
blah efg blah blah

我知道 sed 可以使用两种模式选择范围,例如:

I know sed can select ranges using two patterns, like:

sed -n '/abc/,/efg/p' test.txt

然而,输出将从第一次出现的abc"而不是最后一次开始,输出如下:

However the output will begin from the first occurrence of "abc" instead of the last one, the output is as following:

blah abc blah..
blah abc blah
blah blah..
blah blah..
blah blah..
blah efg blah blah
blah abc blah
blah abc blah
blah abc blah
blah abc blah
blah abc blah
blah blah..
blah efg blah blah

我可以在命令行上进行任何增强,以便输出将从最后一次出现的abc"开始?

Any enhancement can I do on the command line so the output will begin from a last occurrence of "abc"?

推荐答案

这可能对你有用(GNU sed):

This might work for you (GNU sed):

sed -n '/\<abc\>/,/\<efg\>/{/\<abc\>/{h;d};H;/\<efg\>/{x;p}}' file

这篇关于使用 sed 查找两个模式之间的线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆