屬性 : 系統相關 - 文書處理

語法 : sed [參數] [語法] [檔案名稱] 參數 | 功能

-n | 安靜模式, 自動執行
-l N | 指定每一行最多 N 個字元, 超過自動拆行
-s | 將檔案視為分離的, 而不是單獨連續的長字串.

sed 的語法眾多且複雜, 因此這裡只列出兩個常用語法如下 :
'[範圍][動作]/[源字串]/[新字串]/[動作]'
'[字串][動作]/[源字串]/[新字串]/[動作]'

執行範例 :
以下範例將以 testfile 為例說明, testfile內容如下 :

this is line1
start of line
this is line2
this is line2
this is line3
this is line3
end of line

* 將 testfile 的2-3行刪除.
john:~/test2 # sed '2,3d' testfile
start of line
this is line2
this is line3
this is line3
end of line

* 將內容中的第一個 is 字串換程 paper
john:~/test2 # sed 's/is/paper/' testfile
start of line
thpaper is line1
thpaper is line2
thpaper is line2
thpaper is line3
thpaper is line3
end of line
john:~/test2 # sed 's/is/paper/g' testfile <將所有 is 都替換成 paper>
start of line
thpaper paper line1
thpaper paper line2
thpaper paper line2
thpaper paper line3
thpaper paper line3
end of line

* 將含有2 的該行內容中, 若是有 line 這個字串, 全部替換成 special
john:~/test2 # sed '/2/s/line/special/g' testfile
start of line
this is line1
this is special2
this is special2
this is line3
this is line3
end of line

* 把含有 is 這個字串的列全部刪除
john:~/test2 # sed '/is/d' testfile
start of line
end of line

* 把 e 開頭的列全部刪除
john:~/test2 # sed '/^e/d' testfile <如果為 '/^$/d' 即為把所有空白列刪除>
start of line
this is line1
this is line2
this is line2
this is line3
this is line3

* 把含有 3 的字元的列全部列印出來
john:~/test2 # sed -n '/3/p' testfile <-n 是抑制預設秀出全部的動作>
this is line3
this is line3

* 把每一列的頭三個字刪除
john:~/test2 # sed 's/^...//' testfile <'^' 是指開頭, '$'則是結尾, 更多請參考正則表示式>
rt of line
s is line1
s is line2
s is line2
s is line3
s is line3
of line

* 將 is 替換成 is a (不含 this 的is)
john:~/test2 # sed 's/\( is\)/\1 a/g' testfile <把找到的 is 存起來,用 \1 取回來使用, 並使用 ' is' 來區分 this 的 is>
start of line
this is a line1
this is a line2
this is a line2
this is a line3
this is a line3
end of line

* 將 2~4列的 line 字串拿掉
john:~/test2 # sed '2,4s/line//' testfile
start of line
this is 1
this is 2
this is 2
this is line3
this is line3
end of line

補充說明 :
@. sed 與 awk 是 Linux 命令列下強大指令, 對於文書編輯與管理, 都是好用的東西.

若要把/tmp/testfile.log裡的所有數字123取代為數字888,那要如何下指令呢? 如下:

# sed -i 's/123/888/g' /tmp/testfile.log

若要把/tmp/testfile.log裡的所有數字888取代為空白字元(space),那要如何下指令呢? 如下:

# sed -i 's/888/\ /g' /tmp/testfile.log

注意: 空白字元(space)要使用倒斜線(\)來作跳脫特殊字元喔!!!

By tony

自由軟體愛好者~喜歡不斷的思考各種問題,有新的事物都會想去學習嘗試 做實驗並熱衷研究 沒有所謂頂天的技術 只有謙虛及不斷的學習 精進專業,本站主要以分享系統及網路相關知識、資源而建立。 Github http://stnet253.github.io

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料