使用sed压缩多个空行

使用sed压缩多个空行,sed,Sed,我有一个包含空行和动物名称部分的文件: $ cat animals2 cat dog elephant rhino snake hippo eagle camel mouse $ 我想删除除一行以外的所有空行,即输出应为: $ cat animals2 cat dog elephant rhino snake hippo eagle camel mouse $ …或: 我的想法是使用sed处理文件,并且: 读这行字以保留空格 读入模式空间的下一行,并将其与

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

$ cat animals2 



cat
dog
elephant
rhino


snake
hippo

eagle
camel
mouse



$ 
我想删除除一行以外的所有空行,即输出应为:

$ cat animals2 

cat
dog
elephant
rhino

snake
hippo

eagle
camel
mouse

$ 
…或:

我的想法是使用
sed
处理文件,并且:

  • 读这行字以保留空格
  • 读入模式空间的下一行,并将其与保留空间中的行进行比较
  • 如果它们不同,则打印保留空间,然后用图案空间重写保留空间

sed
中是否有方法比较模式空间和保持空间?

由于是多行处理,
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”“;f=0}`如果标志打开,我们到达这里,这意味着当前行有一些内容。因此,我们打印一个空行并停用该标志
  • 1
    执行默认awk操作:打印当前行

由于它是多行处理,
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”“;f=0}`如果标志打开,我们到达这里,这意味着当前行有一些内容。因此,我们打印一个空行并停用该标志
  • 1
    执行默认awk操作:打印当前行

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

cat -s animals2

cat
dog
elephant
rhino

snake
hippo

eagle
camel
mouse
手动猫

-s,--挤压毛坯

抑制重复的空输出行


这个
perl
也可以:

perl -00pe0 < animals2
perl-00pe0
-s
cat
一起使用可能是最简单的解决方案:

cat -s animals2

cat
dog
elephant
rhino

snake
hippo

eagle
camel
mouse
手动猫

-s,--挤压毛坯

抑制重复的空输出行


这个
perl
也可以:

perl -00pe0 < animals2
perl-00pe0
这可能适合您(GNU-sed):

在图案空间中保留两行,仅当两行都不为空时才打印第一行。

这可能适用于您(GNU-sed):

在图案空间中保留两行,仅当两行都不为空时才打印第一行