n 模式: 读取下一行到pattern space,并只处理下一行
N 模式: 将下一行添加到pattern space中,把当前行和下一行一起处理
举个例子
默认情况,读入一行显示/处理一行
$ cat test
a
b
c
d
$ sed '=;p' test
1
a
a
2
b
b
3
c
c
4
d
d
n模式,读入2行,显示/处理第二行
$ sed '=;n;p' test
1
a
b
b
3
c
d
d
N模式,读入2行,显示/处理2行
$ sed '=;N;p' test
1
a
b
a
b
3
c
d
c
d
那么,N模式有什么用? 这就有了著名的sed删除换行符的梗
sed ':a;N;$!ba;s/\n/ /g' file
:a 是定义了个label
N 则是上文的N模式了,一次读入2行,处理2行
Explanation:
1.Create a label via :a.
2.Append the current and next line to the pattern space via N.
3.If we are before the last line, branch to the created label $!ba ($! means not to do it on the last line as there should be one final newline).
4.Finally the substitution replaces every newline with a space on the pattern space (which is the whole file).