sed 是一種在線編輯器,它一次處理一行內容。處理時,把當前處理的行存儲在臨時緩衝區中,稱爲「模式空間」 (pattern space),接着用sed命令處理緩衝區中的內容,處理完成後,把緩衝區的內容送往屏幕。接着處理下一行,這樣不斷重複,直到文件末 尾。文件內容並無 改變,除非你使用重定向存儲輸出。Sed主要用來自動編輯一個或多個文件;簡化對文件的反覆操做;編寫轉換程序等。shell
一下都是對file這個文件進行操做編輯器
文件內容以下spa
a=1
b=2
c=3
z=jxow
a=1
b=2
c=3
z=jxow
a=1
b=2
c=3
z=jxow
a=1
b=2
c=3
z=jxow
server
[root@server1 shell]# sed '1,2d' file #刪除第一,二行的內容
c=3
z=jxow
a=1
b=2
c=3
z=jxow
a=1
b=2
c=3
z=jxow
a=1
b=2
c=3
z=jxow
[root@server1 shell]# sed '7,$d' file #刪除低七行到末尾的內容
a=1
b=2
c=3
z=jxow
a=1
[root@server1 shell]# sed '$d' file #刪除最後一行的內容
a=1
b=2
c=3
z=jxow
a=1
b=2
c=3
z=jxow
a=1
b=2
c=3
z=jxow
a=1
b=2
c=3
字符串
[root@server1 shell]# sed 's/a=1/a=3/' file #替換a=1爲a=3,這個只是簡單的匹配某一行第一個a=1,後面不會進行匹配,若是想匹配,加上參數g,命令格式如sed 's/a=1/a=3/g' file
a=3
b=2
c=3
z=jxow
a=3
b=2
c=3
z=jxow
a=3
b=2
c=3
z=jxow
a=3
b=2
c=3
z=jxow
test
[root@server1 shell]# sed 's/a=1/&a=2/g' file #&符號表示替換換字符串中被找到的部份
a=1a=2
b=2
c=3
z=jxow
a=1a=2
b=2
c=3
z=jxow
a=1a=2
b=2
c=3
z=jxow
a=1a=2
b=2
c=3
z=jxow
sed
[root@server1 shell]# sed -n '/a=1/p' file #找到行中有a=1,參數n要求顯示只是匹配行
a=1
a=1
a=1
a=1
[root@server1 shell]# sed 's#a=1#a=3#g' file #不論什麼字符,緊跟着s命令的都被認爲是新的分隔符,因此,「#」在這裏是分隔符,代替了默認的「/」分隔符。表示把全部a=1替換成a=3file
a=3
b=2
c=3
z=jxow
a=3
b=2
c=3
z=jxow
a=3
b=2
c=3
z=jxow
a=3
b=2
c=3
z=jxow
程序
[root@server1 shell]# sed -n '/a=1/,/c=3/p' file #打印範圍a=1到c=3之間的東西,包括本身
a=1
b=2
c=3
a=1
b=2
c=3
a=1
b=2
c=3
a=1
b=2
c=3重定向
[root@server1 shell]# sed -n '3,/a=1/p' file #打印從第三行開始到第一個包含以a=1開始的行之間的全部行。
c=3
z=jxow
a=1
[root@server1 shell]# sed '/c=3/r test' file #顯示在與c=3匹配的行後面,若是匹配多行,則test的內容將顯示在全部匹配行的下面。
a=1
b=2
c=3
d=4
z=jxow
a=1
b=2
c=3
d=4
z=jxow
a=1
b=2
c=3
d=4
z=jxow
a=1
b=2
c=3
d=4
z=jxow
[root@server1 shell]# sed '/c=3/w test' file #將匹配出來的結果寫到文件test裏面
[root@server1 shell]# cat test
c=3
c=3
c=3
c=3
[root@server1 shell]# sed '/a=1/{n;s/b=2/b=4/g}' file #-若是file被匹配,則移動到匹配行的下一行,替換這一行的b=2,變爲b=4,並打印該行,而後繼續。 a=1b=4c=3z=jxowa=1b=4c=3z=jxowa=1b=4c=3z=jxowa=1b=4c=3z=jxow