1

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.

iamauser
  • 11,119
  • 5
  • 34
  • 52
  • 1
    welcome to SO, here you are expected to show what you've tried yourself to solve this problem.. if you are new to `sed`, you can go through https://stackoverflow.com/tags/sed/info for some faqs and learning resources.. after you've some code that you are stuck with, you could ask here for help.. https://stackoverflow.com/questions/38972736/how-to-select-lines-between-two-patterns/ would be a good starting point for this problem – Sundeep Sep 28 '18 at 12:34

3 Answers3

1

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 :)

Rishu Shrivastava
  • 3,745
  • 1
  • 20
  • 41
0

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

William Pursell
  • 204,365
  • 48
  • 270
  • 300
0

Using Perl

perl -ne ' {  print "Header_one\n" if /Header_one/ ; print if not /Header_one/../^$/ } ' 
stack0114106
  • 8,534
  • 3
  • 13
  • 38