V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
gino86
V2EX  ›  程序员

sed 多行处理的一些疑惑

  •  
  •   gino86 · 2018-03-21 15:16:34 +08:00 · 1634 次点击
    这是一个创建于 2225 天前的主题,其中的信息可能已经有所发展或是发生改变。

    sed 中有多行处理的命令:N、D、P
    现有文件 test.txt ,内容如下:

    line one
    line two
    line three
    line four
    

    分别对 test.txt 执行下面的命令:

    [normal@centos7-server tmp]$ sed -n 'N; /two/P' test.txt
    line one
    [normal@centos7-server tmp]$ sed -n 'N; /one\nline/P' test.txt
    line one
    
    [normal@centos7-server tmp]$ sed 'N; /two/D' test.txt 
    line three
    line four
    [normal@centos7-server tmp]$ sed 'N; /one\nline/D' test.txt
    line two
    line three
    line four
    
    

    N 用于把下一行数据追加到 pattern space,如果没有下一行,则退出循环
    P 打印 pattern sapce 中的第一行数据
    D 删除 pattern space 中的第一行数据,如果 pattern space 中仍然有数据,继续从头执行(不跳到下一个循环)

    上面的例子中两条 P 命令的输出结果一致,我的问题是,为什么两条 D 命令的结果不一致,请问造成这种差异的原因是什么?

    2 条回复    2018-03-21 16:26:40 +08:00
    jasonyang9
        1
    jasonyang9  
       2018-03-21 16:08:30 +08:00   ❤️ 1
    你加个`=;`在表达式前面能看清楚点。

    ```
    sed '=; N; /two/D' test.txt
    1
    2
    3
    line three
    line four
    ```

    ```
    sed '=; N; /one\nline/D' test.txt
    1
    2
    line two
    line three
    4
    line four
    ```
    yyai3
        2
    yyai3  
       2018-03-21 16:26:40 +08:00   ❤️ 1
    我猜是因为 D 命令是从匹配的字符开始删除到换行符,所以 one 开始删除到\n

    https://docstore.mik.ua/orelly/unix/sedawk/appa_03.htm
    D [ address1 [, address2 ]] D
    Delete first part (up to embedded newline) of multiline pattern space created by N command and resume editing with first command in script. If this command empties the pattern space, then a new line of input is read, as if the d command had been executed.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3774 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:36 · PVG 18:36 · LAX 03:36 · JFK 06:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.