Home > Back-end >  How to remove pattern line if next line is empty using sed
How to remove pattern line if next line is empty using sed

Time:11-25

This file, file.txt:

checking
open something
connected
open something
connected
open something

checking
open something

checking
open something
connected
open something

Needs to be like this, file.txt:

checking
open something
connected
open something
connected

checking

checking
open something
connected

We have attempted many sed one liners but with no success.

sed -i "/open/{$!N;/\n.*^$/!P;D}" file.txt

Where open is the pattern, and ^$ is the empty line after pattern.

We would like to delete only the open pattern matching line - if the line after it is empty.

Can someone provide assistance?

CodePudding user response:

GNU sed has the -z option:

sed -rz 's/(^|\n)open[^\n]*\n\n/\1\n/g' file.txt

CodePudding user response:

Sed works on one line only. To do anything on more lines, you have to buffer them in hold space. Let's keep previous line in hold space and just iterate one by one.

sed '
/^$/{
  x
  /open/{
     # Just restart cycle, the line is already in hold space.
     d
  }
  x
}
x
${
    # When it is the last line, print this line and next line.
    p
    x
}
'

CodePudding user response:

An alternative awk approach with some useful tricks...

The entire file can be made a single record by setting the record separator to something that cannot be in the file RS="^$" (see: Awk to read file as a whole).

We can then set the field separator to lines with FS="\n"

Now a loop can be used to check for fields containing the required pattern (in this case, contains open ~/open/) and simultaneously check whether the following line (field) is empty: if ($i~/open/ && $(i 1)=="") When both conditions are met the line can be skipped by using awk's continue command to jump to the next loop iteration.

Working procedure:

awk 'BEGIN{RS="^$";FS="\n";} { for(i=1;i<NF;i  ) { if ($i~/open/ && $(i 1)=="") continue; print $i}  }' file.txt

output:

checking
open something
connected
open something
connected

checking

checking
open something
connected

CodePudding user response:

This might work for you (GNU sed):

sed 'N;/\n$/!P;D' file

Append the following line and if that line is empty do not print the first line. If however it is not empty, print then delete the first line.

  • Related