从文件中提取两个模式之间的行,不包括结束模式匹配

时间:2017-01-08 11:55:46

标签: bash shell awk sed pattern-matching

我想和

一样

Extract lines between two patterns from a file

但我希望打印结尾的行。现在,我想我可以在这个问题的解决方案的结果上进行grep - 但是我可以使sedawk解决方案使用某种前瞻性来打印行匹配结局模式?

2 个答案:

答案 0 :(得分:2)

像这样:

sed -n '/begin/,/end/{/end/!p}'

这将打印begin - end范围内的所有行,但输出中包含end本身的行除外。

答案 1 :(得分:1)

使用awk可以轻松控制它:

$ awk '/begin/{p=1};/end/{p=0};p' input

故障:

/begin/{p=1} # When current line matches `begin' then set p = 1
/end/{p=0}   # When current line matches `end' then set p = 0
p            # Print lines when p is truly, in this case when it's 1.
             # `p' starts empty, and will later be set to 0, which
             # are both falsy values.
             # It's only in the state p = 1 that the lines are printed.

您现在可能会注意到如何移动p以获得不同的结果,即打印beginend之间的行,而不是它自己的行:

p; /begin/{p=1}; /end/{p=0}