ClutchingatStraws
ClutchingatStraws

Reputation: 39

How to code sed to delete multiple lines after a keyword until next blank line reached

Can anyone advise me on how to code a sed script that can be used to update a text file as follows:

Each time a line in the file containing the character string 'Header_one' is encountered: - delete the lines that immediately follow the 'Header_one' line until the next blank line is encountered. - but dont delete the 'Header_one' line itself

So as an example, a file containing this:

Header_one
dkrjng
djsje

Header_two
cklrgjsj
djrhg

Header_one
drgbyj
efgjjm
cddess

Header_three
sdfvgg
ddddfy

Would be changed to:

Header_one

Header_two
cklrgjsj
djrhg

Header_one

Header_three
sdfvgg
ddddfy

I would be grateful for any guidance or solution. Thanks, James.

Upvotes: 1

Views: 80

Answers (3)

Rishu S
Rishu S

Reputation: 3968

Try the below snip

< InputFile sed -e '/Header_one/i Header_one' -e '/Header_one/,/s/d' > outputFile

The idea here is to replace the content between 2 rows and replace it with a header (i.e. Header_one). The second -e part of the codes does delete the data between Header_one and space; while the first -e part replaces it with a new header Header_one.

InputFile and OutputFiles are simple redirections.

You can also look into: https://askubuntu.com/questions/637003/delete-lines-between-2-strings

Hope this helps :)

Upvotes: 1

stack0114106
stack0114106

Reputation: 8791

Using Perl

perl -ne ' {  print "Header_one\n" if /Header_one/ ; print if not /Header_one/../^$/ } ' 

Upvotes: 0

William Pursell
William Pursell

Reputation: 212654

sed is a stream editor, and although one popular version of sed provides an option that appears to make it edit files, I strongly advise against its use. That said, you can produce the output you desire with:

sed -e '/Header_one/i\
Header_one\
\
' -e '/Header_one/,/^$/d' input

Note that it's a lot cleaner if you don't require keeping that blank line:

sed -e '/Header_one/p' -e '/Header_one/,/^$/d' input

Also: awk '/Header_one/{printf "Header_one\n\n"; next } 1' RS= ORS='\n\n' input

Upvotes: 0

Related Questions