如何使用awk/sed选择可能多次出现的两个标记模式之间的线 [英] How to select lines between two marker patterns which may occur multiple times with awk/sed

查看:41
本文介绍了如何使用awk/sed选择可能多次出现的两个标记模式之间的线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 awksed 如何选择出现在两个不同标记模式之间的行?可能有多个部分标有这些模式.

Using awk or sed how can I select lines which are occurring between two different marker patterns? There may be multiple sections marked with these patterns.

例如:假设文件包含:

abc
def1
ghi1
jkl1
mno
abc
def2
ghi2
jkl2
mno
pqr
stu

起始模式为abc,结束模式为mno所以,我需要输出为:

And the starting pattern is abc and ending pattern is mno So, I need the output as:

def1
ghi1
jkl1
def2
ghi2
jkl2

我使用 sed 来匹配模式一次:

I am using sed to match the pattern once:

sed -e '1,/abc/d' -e '/mno/,$d' <FILE>

sedawk 有没有办法重复执行直到文件结束?

Is there any way in sed or awk to do it repeatedly until the end of file?

推荐答案

使用带有标志的 awk 以在必要时触发打印:

Use awk with a flag to trigger the print when necessary:

$ awk '/abc/{flag=1;next}/mno/{flag=0}flag' file
def1
ghi1
jkl1
def2
ghi2
jkl2

这是如何工作的?

  • /abc/ 匹配具有此文本的行,就像 /mno/ 一样.
  • /abc/{flag=1;next} 在找到文本 abc 时设置 flag.然后,它跳过该行.
  • /mno/{flag=0} 在找到文本 mno 时取消设置 flag.
  • 最后的 flag 是一个带有默认动作的模式,即 print $0:如果 flag 等于 1,则打印该行.
  • /abc/ matches lines having this text, as well as /mno/ does.
  • /abc/{flag=1;next} sets the flag when the text abc is found. Then, it skips the line.
  • /mno/{flag=0} unsets the flag when the text mno is found.
  • The final flag is a pattern with the default action, which is to print $0: if flag is equal 1 the line is printed.

有关更详细的描述和示例,以及模式显示与否的情况,请参阅如何选择两条线之间的线模式?.

For a more detailed description and examples, together with cases when the patterns are either shown or not, see How to select lines between two patterns?.

这篇关于如何使用awk/sed选择可能多次出现的两个标记模式之间的线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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