没有序言,
$ cat in.txt a b c d $ sed '=;N' in.txt 1 a b 3 c d
看起来'N'命令适用于其他每一行.也许这很自然,因为命令'N'加入下一行并改变当前行号.但,
$ sed 'N;$!P;$!D;$d' thegeekstuff.txt
(我在这里看到这个)
上面的例子删除了文件的最后两行.这不仅适用于偶数行编号的文件,也适用于奇数行编号的文件.因此,在此示例中,'N'命令在每一行上运行.
有什么区别?
你能不能告诉我为什么当我像这样运行sed时我看不到最后一行?
# sed N odd-lined-file.txt
ssa*_*ota 26
摘录自info sed:
`sed' operates by performing the following cycle on each lines of
input: first, `sed' reads one line from the input stream, removes any
trailing newline, and places it in the pattern space. Then commands
are executed; each command can have an address associated to it:
addresses are a kind of condition code, and a command is only executed
if the condition is verified before the command is to be executed.
...
When the end of the script is reached, unless the `-n' option is in
use, the contents of pattern space are printed out to the output
stream,
...
Unless special commands (like 'D') are used, the pattern space is
deleted between two cycles
...
`N'
Add a newline to the pattern space, then append the next line of
input to the pattern space. If there is no more input then `sed'
exits without processing any more commands.
...
`D'
Delete text in the pattern space up to the first newline. If any
text is left, restart cycle with the resultant pattern space
(without reading a new line of input), otherwise start a normal
new cycle.
Run Code Online (Sandbox Code Playgroud)
这应该可以解决您的查询问题.但我仍然会尝试解释你的三种不同情况:
情况1:
sed从输入中读取一行.[ 现在模式空间中有1行.]= 打印当前行号.N将下一行读入模式空间.[ 现在模式空间中有2行.]
sed打印图案空间并清理它.[ 图案空间是空的.]EOF到达sed这里退出.否则从步骤1重新开始完整循环. [ 即:如果是偶数行,则sed退出此处.]简介:在这种情况下,sed读取2行并一次打印2行.吞下最后一行,有奇数行(见步骤3).
案例2:
sed从输入中读取一行.[ 现在模式空间中有1行.]N将下一行读入模式空间.[ 现在模式空间中有2行.]
$!(P)从模式空间打印第一行().[ 打印图案空间的第一行.但模式空间中仍有2行.]$!)D从模式空间中删除第一行()现在模式空间中只有一行(第二行).]并从步骤2重新启动命令循环.由于该命令D (请参阅上面的摘录).$)然后删除(d)完整的模式空间.[即.达到EOF] [ 在开始此步骤之前,模式空间中有2行现在被清除d- 在此步骤结束时,模式空间为空.]sed 自动停在EOF.摘要:在这种情况下:
sed 首先读取2行.情况3:
与CASE:1的情况相同,只需从中删除第2步.