sed '1{n};p' file
发表于 : 2011-12-17 23:16
file内容如下:
bells@bells-VirtualBox ~ $ cat file
line1
line2
line3
执行命令如下:
bells@bells-VirtualBox ~ $ sed '1{n};p' file
line1
line2
line2
line3
line3
我想知道为什么line1会被输出,而且line2和line3会被输出两次??
我自己的分析:
当读第一行时, line1进入pattern space中,当执行 '1{n};p'的时候,碰到n,所以读入第二行即"line2",然后碰到p,所以输出"line2",然后读入第三行.....
想不通"line1"是什么时候输出的??还有多余的"line2"和"line3"
然后我用命令:
bells@bells-VirtualBox ~ $ sed -n '1{n};p' file
line2
line3
的输出结果符合我的分析
所以问题出在"-n"身上。。。难道sed默认当读入新的一行,就立刻输出该行的内容,而不先执行命令??
下面是info sed中的部分内容:
`sed' maintains two data buffers: the active _pattern_ space, and the
auxiliary _hold_ space. Both are initially empty.
`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, adding back the trailing newline if it was removed.(1) Then the
next cycle starts for the next input line.
bells@bells-VirtualBox ~ $ cat file
line1
line2
line3
执行命令如下:
bells@bells-VirtualBox ~ $ sed '1{n};p' file
line1
line2
line2
line3
line3
我想知道为什么line1会被输出,而且line2和line3会被输出两次??
我自己的分析:
当读第一行时, line1进入pattern space中,当执行 '1{n};p'的时候,碰到n,所以读入第二行即"line2",然后碰到p,所以输出"line2",然后读入第三行.....
想不通"line1"是什么时候输出的??还有多余的"line2"和"line3"
然后我用命令:
bells@bells-VirtualBox ~ $ sed -n '1{n};p' file
line2
line3
的输出结果符合我的分析
所以问题出在"-n"身上。。。难道sed默认当读入新的一行,就立刻输出该行的内容,而不先执行命令??
下面是info sed中的部分内容:
`sed' maintains two data buffers: the active _pattern_ space, and the
auxiliary _hold_ space. Both are initially empty.
`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, adding back the trailing newline if it was removed.(1) Then the
next cycle starts for the next input line.