user3735276
user3735276

Reputation: 27

SED Delete line Previous the Match and Proceeding Line

I have a file that has text like this:

Begin  
Certificate  
End  

Begin  
PKIValue1  
End  

Begin  
PKIValue2  
End  

Begin  
Certificate  
End

I want to remove the three lines associated with Certificate but keep the remaining Begin and End for the PKIValues.

I have been testing with this SED line:

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

That line does the opposite of what I want. It keeps only the Certificate value and the associated Begin and End. How can I delete the certificate but keep the other lines for PKIValues?

Upvotes: 1

Views: 93

Answers (2)

Jotne
Jotne

Reputation: 41460

This small gnu awk should do:

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

Begin
PKIValue2
End

Setting RS record selector to nothing makes it work in block mode (gnu function)
!/Certificate/' this just remove blocks with Certificate

This works fine if there are various number of lines in the block.

Upvotes: 1

John1024
John1024

Reputation: 113984

Consider:

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

Begin
PKIValue2
End

How it works

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

Every time there is a Begin line, we gather it and the next three lines, N;N;N;, into the pattern space. If the pattern space now contains Certificate, we skip this grouping. If it doesn't, we print it.

Upvotes: 1

Related Questions