Linux ';N';和';D';使用sed时未按预期工作 sed'N;D'测试文件

Linux ';N';和';D';使用sed时未按预期工作 sed'N;D'测试文件,linux,sed,Linux,Sed,测试文件包含: this is the first line this is the second line this is the third line this is the fourth line 我正在使用RHEL 6,输出如下: this is the fourth line 根据我的理解,N只将下一行拉入模式空间,D只删除模式空间的第一行。因此,输出应为: this is the second line this is the fourth line 有人能解释一下为什么会出现

测试文件包含:

this is the first line
this is the second line
this is the third line
this is the fourth line
我正在使用RHEL 6,输出如下:

this is the fourth line
根据我的理解,
N
只将下一行拉入模式空间,
D
只删除模式空间的第一行。因此,输出应为:

this is the second line
this is the fourth line
有人能解释一下为什么会出现上述输出吗?

根据:

D

如果模式空间不包含换行符,则开始一个正常的新循环,就像发出了d命令一样。否则,删除模式空间中直到第一个换行符的文本,重新启动循环,使用生成的模式空间,而不读取新的输入行

(我的重点。)


这听起来像是从一开始就重新启动sed程序,读取和删除行,直到输入用完,此时缓冲区中只剩下最后一行。

如使用
D所示,将移动到程序的开头。但是,您可以使用以下方法打印偶数行:

sed -n 'n;p'
打印赔率:

sed 'n;d'
在GNU sed中,您还可以使用:

sed '0~2!d' # Odd
sed '1~2!d' # Even
另一种选择是:

N;s/^[^\n]*\n//
这将读取模式空间中的下一行,然后替换第一行

有人可能会问,为什么会有这种行为。一个原因是为了使类似的事情成为可能,在模式空间中使用多行:

$!N;/\npattern$/d;P;D
以上将删除匹配模式的行以及之前的行