用sed挤压多个空行

时间:2014-11-24 15:34:11

标签: sed

我有一个空行和动物名称部分的文件:

$ cat animals2 



cat
dog
elephant
rhino


snake
hippo

eagle
camel
mouse



$ 

我想删除所有空行,即输出,即输出应为:

$ cat animals2 

cat
dog
elephant
rhino

snake
hippo

eagle
camel
mouse

$ 

..或:

$ cat animals2 

cat
dog
elephant
rhino

snake
hippo

eagle
camel
mouse
$ 

我的想法是使用sed

处理文件
  • 读取行以保留空间
  • 在下一行中读取模式空间并将其与保留空间中的行进行比较
  • 如果它们不同,则打印保留空间,然后用图案空间重写保留空间

有没有办法比较sed中的模式空间和保留空间?

3 个答案:

答案 0 :(得分:3)

由于它是多线处理,awk可以更有效地完成:

awk '!NF {f=1; next} f {print ""; f=0} 1' file

它返回:


cat
dog
elephant
rhino

snake
hippo

eagle
camel
mouse

解释

  • !NF {f=1; next}如果没有字段 - >这条线是空的 - >我们设置了一个标志,我们跳转到下一行而没有进一步的操作。
  • f {print"&#34 ;; f = 0}`如果标志打开并且我们到达此处,则表示当前行有一些内容。因此,我们打印一个空行并停用该标志。
  • 1执行默认的awk操作:打印当前行。

答案 1 :(得分:1)

-scat一起使用可能是最简单的解决方案:

cat -s animals2

cat
dog
elephant
rhino

snake
hippo

eagle
camel
mouse

来自man cat

  

-s , - squeeze-blank

     

抑制重复的空输出线


perl也可以:

perl -00pe0 < animals2

答案 2 :(得分:1)

这可能适合你(GNU sed):

sed 'N;/^\n$/!P;D' file

在图案空间中保留两行,并且只有当两者都不为空时才打印第一行。

相关问题