sed 多行处理的一些疑惑

2018-03-21 15:16:34 +08:00
 gino86

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

1639 次点击
所在节点    程序员
2 条回复
jasonyang9
2018-03-21 16:08:30 +08:00
你加个`=;`在表达式前面能看清楚点。

```
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
2018-03-21 16:26:40 +08:00
我猜是因为 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.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/440081

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX