How to delete one blank row and the following row only if it is not empty

Viewed 65

I have a two column file with a structure

1 2
10 1

10 1
10 3
102 40


102 40 
25 5
53 4

53 4
35 6
64 5
456 4


456 4
243 535
435 6

So number above and below the blank row are same. But the blank row are not uniform (they are single, double or triple). I want to delete the number just after the each blank row and the blank row just above this number.

My expected output should be like this

1 2
10 1
10 3
102 40

25 5
53 4
35 6
64 5
456 4

243 535
435 6

I have tried to do this:

sed -e '/pattern/,+1d' input_file 

You see my pattern is varying and I failed to solve the issue.

2 Answers

This might work for you (GNU sed):

sed 'N;/^\n\S/d;P;D' file

Open a two line window throughout the length of the file.

If the first line of the window is empty and the second is not, delete both lines.

Otherwise, print/delete the first line and repeat.

With GNU sed and input file small enough to fit memory:

$ # or: perl -0777 -pe 's/\n\n\N+//g' ip.txt
$ sed -zE 's/\n\n[^\n]+//g' ip.txt
1 2
10 1
10 3
102 40

25 5
53 4
35 6
64 5
456 4

243 535
435 6

This will match empty line and delete another line only if it contains any character. The sed solution assumes input doesn't contain ASCII NUL characters, because -z uses NUL as line separator.


With GNU awk

awk -v RS='\n\n[^\n]+' -v ORS= '1' ip.txt
Related