sed 'N; D' testfile
testfile包含:
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
有人可以解释为什么输出如上所述?
答案 0 :(得分:4)
d
如果模式空间不包含换行符,则启动正常的新循环,就像发出d命令一样。否则,删除模式空间中直到第一个换行符的文本,并使用生成的模式空间重新启动循环,而不读取新的输入行。
(强调我的。)
听起来这会从头开始重新启动你的sed程序,读取和删除行,直到输出用完为止,此时只有最后一行留在缓冲区中。
答案 1 :(得分:1)
如前所示,使用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
以上将删除匹配模式的行以及之前的行。