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 命令的结果不一致,请问造成这种差异的原因是什么?
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 ``` |
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. |