linux shell脚本实现删除连续的空行为一行

发布时间 2023-07-11 23:07:23作者: 小鲨鱼2018

 

001、awk实现

[root@PC1 test02]# ls
a.txt
[root@PC1 test02]# cat a.txt          ## 测试数据
01 02 03 04 05
06 07 08 09 10



11 12 13 14 15
16 17 18 19 20

21 22 23 24 25
26 27 28 29 30                        ## 将多个连续的空行压缩为一个空行
[root@PC1 test02]# awk 'BEGIN{tag = 0} {if($0 ~ /^$/) {tag++} else {tag = 0}; if(tag > 1) {next} else {print $0}}' a.txt
01 02 03 04 05
06 07 08 09 10

11 12 13 14 15
16 17 18 19 20

21 22 23 24 25
26 27 28 29 30

 

002、sed实现

[root@PC1 test02]# ls
a.txt
[root@PC1 test02]# cat a.txt
01 02 03 04 05
06 07 08 09 10



11 12 13 14 15
16 17 18 19 20

21 22 23 24 25
26 27 28 29 30
[root@PC1 test02]# sed '/^$/{N;/^\n$/d}' a.txt    ## 将多个连续的空行转换为单个空行
01 02 03 04 05
06 07 08 09 10

11 12 13 14 15
16 17 18 19 20

21 22 23 24 25
26 27 28 29 30

 。