command description
P 打印 pattern space 中的一行
D 删除当前 pattern space 的一行,并重新开始新的循环
N 读取输入源的下一行,并追加到 pattern space,使用 newline 分隔,并继续当前循环的执行(execution of cycle)

一行指的是,使用行分隔符分隔

sed 命令中,似乎有这样的规约:大写字母的命令总是与多行数据相关的;通常利用这些命令实现一个队列 FIFO.

例子:移除文件中最后5行:

1
2
3
4
5
6
7
cat -n inputfile | sed -En -e '
1 { N;N;N;N } # ensure the pattern space contains *five* lines

N # append a sixth line onto the queue
P # Print the head of the queue
D # Remove the head of the queue
'

利用可以追加(N - read and append)到 pattern space 的命令,以及删除(D) pattern space 中首行的命令,可以在 pattern space 中保持一个大小为 5 的队列,当第 6 行的数据追加到 pattern space 时,出队,即打印(P)队首的元素, 并删除(D)队首的行, 最终 pattern space 中保留了最后 5 行的数据,其余行已经打印,到达文件末尾,执行结束。

参考链接

Complete Sed Command Guide