如何使用sed仅删除双空行? [英] How to use sed to remove only double empty lines?

查看:278
本文介绍了如何使用sed仅删除双空行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在问题和答案上找到了如何删除三重空行.但是,仅双倍空行需要相同的内容. IE.应当完全删除所有双空行,但应保留单空行.

I found this question and answer on how to remove triple empty lines. However, I need the same only for double empty lines. Ie. all double blank lines should be deleted completely, but single blank lines should be kept.

我对sed有点了解,但是建议的删除三行空白行的命令却浮在我的头上:

I know a bit of sed, but the proposed command for removing triple blank lines is over my head:

sed '1N;N;/^\n\n$/d;P;D'

推荐答案

我已经注释了您不理解的sed命令:

I've commented the sed command you don't understand:

sed '
    ## In first line: append second line with a newline character between them.
    1N;
    ## Do the same with third line.
    N;
    ## When found three consecutive blank lines, delete them. 
    ## Here there are two newlines but you have to count one more deleted with last "D" command.
    /^\n\n$/d;
    ## The combo "P+D+N" simulates a FIFO, "P+D" prints and deletes from one side while "N" appends
    ## a line from the other side.
    P;
    D
'

删除1N是因为我们只需要'stack'中的两行,第二个N就足够了,然后将/^\n\n$/d;更改为/^\n$/d;以删除所有两个连续的空白行.

Remove 1N because we need only two lines in the 'stack' and it's enought with the second N, and change /^\n\n$/d; to /^\n$/d; to delete all two consecutive blank lines.

测试:

infile的内容:

1


2
3

4



5

6


7

运行sed命令:

sed '
    N;
    /^\n$/d;
    P;
    D
' infile

结果是:

1
2
3

4

5

6
7

这篇关于如何使用sed仅删除双空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆