1

I am struggling to use sed to work through 'testfile.txt' and every time it encounters a line that starts delete_me: abc it will then:

  1. leave the line delete_me: abc intact
  2. but delete all the lines that follow until the next blank line is reached in the file.

eg. I want this input:

delete_me: abc
sSAsaAaSA
AsaSAsaSAsa
asASAsS

^--- <blank line>

...to be changed to just this one line:

delete_me: abc

I have tried:

sed '/delete_me/ {n;d}' jil_testfile.txt
# deletes only the first line after 'delete_me'

sed '/delete_me/,/^$/d' jil_testfile.txt
# nearly works but deletes the 'delete_me' line too which I want to stay preserved.

Any suggestions please?

smci
  • 32,567
  • 20
  • 113
  • 146
  • Generally, if you need to preserve state over multiple lines, better to use awk or perl, the code is cleaner. – smci Sep 28 '18 at 14:53
  • This question is different since you want to **delete a variable number of lines after pattern1, until you match pattern2 (blank line,in your case)**. The more basic task is [sed or awk: delete n lines following a pattern](https://stackoverflow.com/questions/4396974/sed-or-awk-delete-n-lines-following-a-pattern) – smci Sep 28 '18 at 15:00

1 Answers1

1

This might work for you (GNU sed):

sed -n ':a;/delete_me/{p;:b;n;//ba;bb};p' file

Print lines as normal until the first occurrence of delete_me. Print this line and do not print any further lines unless that line contains delete_me.

As the spec has changed since I wrote the first solution, here is new one:

sed -n '/delete_me/{p;:a;n;/^$/b;ba};p' file
potong
  • 55,640
  • 6
  • 51
  • 83