SED删除行上一个匹配和进行行

时间:2015-02-13 18:34:39

标签: sed

我的文件有这样的文字:

Begin  
Certificate  
End  

Begin  
PKIValue1  
End  

Begin  
PKIValue2  
End  

Begin  
Certificate  
End

我想删除与Certificate相关联的三行,但保留Begin的剩余EndPKIValues

我一直在测试这条SED系列:

sed -n -e '/Certificate/{x;1!p;g;$!N;p;D;}' -e h $cert_file>PKI.txt

这条线与我想要的相反。它仅保留Certificate值以及关联的BeginEnd。如何删除certificate,但保留PKIValues的其他行?

2 个答案:

答案 0 :(得分:1)

考虑:

$ sed -n -e '/Begin/{N;N;N;/Certificate/!p;}' file
Begin
PKIValue1
End

Begin
PKIValue2
End

如何运作

`/Begin/{N;N;N;/Certificate/!p;}`

每次有Begin行时,我们会将它和接下来的三行N;N;N;收集到模式空间中。如果模式空间现在包含Certificate,我们将跳过此分组。如果没有,我们就打印出来。

答案 1 :(得分:1)

这个小gnu awk应该:

awk '!/Certificate/' RS= ORS="\n\n" file
Begin
PKIValue1
End

Begin
PKIValue2
End

RS记录选择器设置为空,使其在块模式下工作(gnu功能)
!/Certificate/'这只是删除Certificate

的块

如果块中有不同数量的行,则可以正常工作。