如何使用awk/sed选择可能多次出现的两个标记模式之间的线 [英] How to select lines between two marker patterns which may occur multiple times with awk/sed
问题描述
使用 awk
或 sed
如何选择出现在两个不同标记模式之间的行?可能有多个部分标有这些模式.
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>
sed
或 awk
有没有办法重复执行直到文件结束?
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 theflag
when the textabc
is found. Then, it skips the line./mno/{flag=0}
unsets theflag
when the textmno
is found.- The final
flag
is a pattern with the default action, which is toprint $0
: ifflag
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屋!