Reputation: 2249
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
Reputation: 41446
Here is an awk
solution:
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
Reputation: 10039
sed '/^$/ {
:a
N
/\n$/ ba
d
}' YourFile
Upvotes: 1
Reputation: 37023
Try something like:
sed '/^$/,+1 d' test.txt
whenever you find an empty line, delete it and next immediate line.
Upvotes: 5