next up previous contents
Next: 再進一步 Up: sed command命令 Previous: 基本指令   Contents

pattern/hold space的處理

l跟p的差別在對非ASCII的處理
	cyril@gyoza:~$ cat last
	第一行  first line
	第二行  second line
	最後一行  last line

	cyril@gyoza:~$ sed '1,2p' last
	第一行  first line
	第一行  first line
	第二行  second line
	第二行  second line
	最後一行  last line

	cyril@gyoza:~$ sed '1,2l' last
	\262\304\244@\246\346  first line$
	第一行  first line
	\262\304\244G\246\346  second line$
	第二行  second line
	最後一行  last line
這邊可以對pattern space有更深的了解,第一行進到pattern space 看到p把第一行印出,接著pattern space變成output,所以sed又把 他印一遍,接著第二行進來了,在pattern space裡,看到p把第二行印出, 同理又有兩個第二行被印出,第三行由於p沒作用,直接是pattern space 送到output。再看一個例子(抄出來的)
	cyril@gyoza:~$ cat command.txt
	This describes the Linux ls command.
	This describes the Linux cp command.
	
	cyril@gyoza:~$ cat command.sed
	/Linux/{
	h
	s/.* Linux \(.*\) .*/\1:/
	p
	x
	}
	
	cyril@gyoza:~$ sed -f command.sed command.txt
	ls:
	This describes the Linux ls command.
	cp:
	This describes the Linux cp command.

	或者寫成一行
cyril@gyoza:~$ sed '/Linux/{h;s/.* Linux \(.*\) .*/\1:/;p;x;}' command.txt
這邊看第一個h把第一行推進hold space,不過記住pattern space還保有 原本第一行的句子。然後代換掉變成ls:,現在pattern space只有ls:, 然後p印出ls:,最後把hold space跟ls:交換,所以最後pattern space內 就是原本的東西,被sed當成output送出,cp是同樣的道理。

所以沒什麼,只是兩個眼睛看不到的space在那邊換來換去,把內容在這兩個 地方加加減減copy/paste就好了。如果熟悉vi的人應該很容易體會。

Cyril Huang 2002-06-14