简体   繁体   中英

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?

Try something like:

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

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

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
sed '/^$/ {
:a
   N
   /\n$/ ba
   d
   }' YourFile
  • Posix version
  • remove ALL continuous empty line and next (non empty) one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM