简体   繁体   English

Shell脚本删除空行旁边的行

[英]Shell script to delete a line next to empty lines

I'm able to delete empty lines from a file using grep or sed . 我可以使用grepsed从文件中删除空行。 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解决方案:

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. !NF {f=1;next}如果行为空白,则设置f=1并跳过该行。
Then if line is not blank, test if f is true. 然后,如果行不是空白,则测试f是否为真。
{f=0;next} if its true, set f=0 and skip the line. {f=0;next}如果为true,则设置f=0并跳过该行。
1 print the remaining line. 1打印剩余的行。


And some gofling done by ED ED做的一些事情

awk 'NF&&!f;{f=!NF}' file
sed '/^$/ {
:a
   N
   /\n$/ ba
   d
   }' YourFile
  • Posix version Posix版本
  • remove ALL continuous empty line and next (non empty) one 删除所有连续的空行和下一个(非空)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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