Linux運維三劍客學習知識中,sed執行流程是怎樣的?老男孩教育Linux培訓帶你們一塊兒來看看。html
1.讀取文件(從文件或管道)的第1行
2.讀取到sed使用的內存區域中(模式空間)
3.進行判斷這一行是不是我要的less1.若是是則則執行對應的命令(p d c a i s )
2.若是不是則讀取下一行(注若是沒加上-n sed會默認顯示這行內容(模式空間內容))運維
詳細過程必定要看官方的說明:info sedide
`sed' maintains two data buffers: the active pattern space, and the
auxiliary hold space. Both are initially empty.學習
sed命令包含兩個用來存放數據的內存區域(兩個buffer區域):spa
pattern space 模式空間
hold sapce 保持空間
兩個空間默認都是空的code
`sed' operates by performing the following cycle on each line of
input:orm
sed命令的執行過程(一個循環過程)以下所示:htm
first, `sed' reads one line from the input stream, removes any
trailing newline, and places it in the pattern space.blog
第1步,sed從輸入(文件或管道)中讀取1行,刪除每一行的回車符號而後存放在模式空間(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.
第2步,開始執行對應的命令,每一個命令前面能夠有一個條件(地址),只有知足條件的時候纔會執行對應的命令(p d s c a i等等).
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.
第3步,當命令執行完成(這裏命令指的是sed內部的p d s c a i 等等),若是沒有-n參數(取消sed命令默認輸出)則sed會把當前模式空間的內容顯示出來而後再加上1個回車(第1步被刪除的).而後開始讀取下一行,進行下一個循環.
Unless special commands (like D') are used, the pattern space is deleted between two cycles. The hold space, on the other hand, keeps its data between cycles (see commands
h', H',
x', g',
G' to move
data between both buffers).
補充說明:
模式空間的內容會在每一個循環結束後清空(除非加上D)。
保持空間的內容會在每次循環之間保留不被清空 (經過 h H x g G 移動保持空間和模式空間的數據)
(1) Actually, if sed' prints a line without the terminating newline, it will nevertheless print the missing newline as soon as more text is sent to the same output stream, which gives the "least expected surprise" even though it does not make commands like `sed -n p' exactly identical to cat'.
實際上,sed若是顯示沒有回車的行,他會在你屢次顯示到相同輸出的時候替你加上缺乏的回車。這個特色sed -n p 和cat並不徹底相同.
這算是極特殊用法了,瞭解便可.
[root@oldboyedu-show01 ~]# cat old.txt #這個文件就沒有回車 oldboy[root@oldboyedu-show01 ~]# [root@oldboyedu-show01 ~]# sed -n p old.txt #經過sed顯示的時候 沒有顯示每行的結尾 oldboy[root@oldboyedu-show01 ~]# [root@oldboyedu-show01 ~]# sed -n p old.txt old.txt old.txt #屢次輸出的時候sed會自動加上 回車 oldboy oldboy oldboy[root@oldboyedu-show01 ~]# [root@oldboyedu-show01 ~]# cat old.txt old.txt old.txt #一樣輸出到相同的地方(屏幕) cat不會自動加上回車 oldboyoldboyoldboy[root@oldboyedu-show01 ~]#