codedoc
codedoc

Reputation: 2249

Shell script to delete a line next to empty lines

I'm able to delete empty lines from a file using grep or sed. But, I'm unable to resolve a scenario where I have to delete a valid line next to empty lines. Following is an example:

Source:

1_1
1_2
1_3
1
2_1
2_2
2_3
2_4
2_5
2

3
4_1
4_2
4
5_1
5_2
5_3
5_4
5



6
7_1
7
8_1
8_2
8

Output:

1_1
1_2
1_3
1
2_1
2_2
2_3
2_4
2_5
2
4_1
4_2
4
5_1
5_2
5_3
5_4
5
7_1
7
8_1
8_2
8

How to delete the valid line next to empty lines?

Upvotes: 0

Views: 409

Answers (3)

Jotne
Jotne

Reputation: 41446

Here is an awksolution:

awk '!NF {f=1;next} f {f=0;next}1' file
1_1
1_2
1_3
1
2_1
2_2
2_3
2_4
2_5
2
4_1
4_2
4
5_1
5_2
5_3
5_4
5
7_1
7
8_1
8_2
8

!NF {f=1;next} if line is blank, set f=1 and skip the line.
Then if line is not blank, test if f is true.
{f=0;next} if its true, set f=0 and skip the line.
1 print the remaining line.


And some gofling done by ED

awk 'NF&&!f;{f=!NF}' file

Upvotes: 2

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed '/^$/ {
:a
   N
   /\n$/ ba
   d
   }' YourFile
  • Posix version
  • remove ALL continuous empty line and next (non empty) one

Upvotes: 1

SMA
SMA

Reputation: 37023

Try something like:

sed '/^$/,+1 d' test.txt

whenever you find an empty line, delete it and next immediate line.

Upvotes: 5

Related Questions