如何使用sed只删除双空行?

mar*_*lar 25 regex linux sed

我找到了关于如何删除三条空行的问题和答案.但是,我只需要双空行.IE浏览器.应完全删除所有双空行,但应保留单个空白行.

我知道一点sed,但建议的删除三个空行的命令是我的头脑:

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

Der*_*ike 54

这将更容易cat:

cat -s
Run Code Online (Sandbox Code Playgroud)

  • 从来不知道这一点,但正是我所需要的.很好找. (6认同)

Bir*_*rei 14

我评论了sed你不理解的命令:

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
'
Run Code Online (Sandbox Code Playgroud)

删除1N,因为我们只需要两个在"叠加"线,它与第二足够多N,并改变/^\n\n$/d;/^\n$/d;删除所有两个连续的空行.

一个测试:

内容infile:

1


2
3

4



5

6


7
Run Code Online (Sandbox Code Playgroud)

运行sed命令:

sed '
    N;
    /^\n$/d;
    P;
    D
' infile
Run Code Online (Sandbox Code Playgroud)

产量:

1
2
3

4

5

6
7
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢,这个命令可以做到:sed'N;/^ \n $/d; P; D' (2认同)

Tho*_*hor 7

这将更容易awk:

awk -v RS='\n\n\n' 1
Run Code Online (Sandbox Code Playgroud)


小智 6

sed '/^$/{N;/^\n$/d;}'
Run Code Online (Sandbox Code Playgroud)

它将仅删除文件中的两个连续空行.您只能在文件中使用此表达式,然后才能完全理解.当一个空白行出现时,它将进入大括号.

通常sed会读一行.N将第二行附加到模式空间.如果该行是空行.这两行由换行符分隔.

/^\n$/这个模式将匹配那个时间只有d工作.否则d不行.d用于删除模式空间的整个内容然后开始下一个循环.

  • sed'N; / ^ \ n $ / D; P; D;' 似乎效果更好,并且仅删除连续的换行符 (2认同)