V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
gino86
V2EX  ›  程序员

sed 多行处理的一些疑惑

  •  
  •   gino86 · Mar 21, 2018 · 2291 views
    This topic created in 2972 days ago, the information mentioned may be changed or developed.

    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 replies    2018-03-21 16:26:40 +08:00
    jasonyang9
        1
    jasonyang9  
       Mar 21, 2018   ❤️ 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  
       Mar 21, 2018   ❤️ 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.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1021 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 18:30 · PVG 02:30 · LAX 11:30 · JFK 14:30
    ♥ Do have faith in what you're doing.