如何使用sed在2个模式之间打印线条

时间:2013-04-22 18:43:43

标签: sed awk

如何在pattern1和pattern2之间打印线条,我不需要在pattern1和pattern3之间使用线条。

请以sed,awk建议解决方案。

我有这样的情况。

pattern1
blah blah blah
blah blah blah
blah blah blah
pattern2
pattern1
blah blah blah
blah blah blah
pattern3
pattern1
blah blah blah
blah blah blah
pattern2
pattern1
blah blah blah 
blah blah blah
pattern3

欲望输出:

pattern1
blah blah blah
blah blah blah
blah blah blah
pattern2
pattern1
blah blah blah
blah blah blah
pattern2

4 个答案:

答案 0 :(得分:5)

使用sed:

sed -n '/pattern1/{:l N;/pattern3/b;/pattern2/!bl;p}' input

<强>描述

/pattern1/{   # Match pattern1 and ...
:l N;         # start loop and read a line
/pattern3/b   # quit if pattern3 matches
/pattern2/!bl # loop until pattern2 matches
 p            # print all lines

<强>输出

pattern1
blah blah blah
blah blah blah
blah blah blah
pattern2
pattern1
blah blah blah
blah blah blah
pattern2

答案 1 :(得分:3)

一种方法:

$ awk '/pattern1/{s=1;f=1;s=NR}f{p[NR]=$0}/pattern3/{s=0}/pattern2/&&s{f=0;for(i=s;i<=NR;i++)print p[i]}' file
pattern1
blah blah blah
blah blah blah
blah blah blah
pattern2
pattern1
blah blah blah
blah blah blah
pattern2

答案 2 :(得分:2)

$ awk '/pattern1/{f=!f;buf=""} f{buf = buf $0 ORS} /pattern2/{if(f)printf "%s",buf; f=0} /pattern3/{f=0}' file
pattern1
blah blah blah
blah blah blah
blah blah blah
pattern2
pattern1
blah blah blah
blah blah blah
pattern2

为了帮助理解,这里是上面的几行和更多的变量名称:

awk '
/pattern1/ {
    found=!found
    buffer=""
}

found {
    buffer = buffer $0 ORS
}

/pattern2/ {
    if (found) {
        printf "%s",buffer
    }
    found=0
}

/pattern3/ {
    found=0
}
' file

答案 3 :(得分:1)

我在纯粹的解决方案中迷失了我的空间;所以这里有另一种选择

$ tac input | sed '/pattern3/,/pattern1/d' | tac
pattern1
blah blah blah
blah blah blah
blah blah blah
pattern2
pattern1
blah blah blah
blah blah blah
pattern2