Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux 伺服器

sed 入門:非互動式文字串流編輯器用法整理

sed 是一個非互動式的文字串流編輯器,它讀取檔案或標準輸入,把處理後的結果輸出。它最適合用在批次替換、抽取特定行、插入或刪除內容這類反覆出現的文字工作。

比對與列印特定行

[root@mypc /]# sed -n '2p' /etc/passwd        # 印出第 2 行
[root@mypc /]# sed -n '1,3p' /etc/passwd      # 印出第 1 至 3 行
[root@mypc /]# sed -n '$p' /etc/passwd        # 印出最後一行
[root@mypc /]# sed -n '/user/p' /etc/passwd   # 印出含 user 的行
[root@mypc /]# sed -n '/\$/p' /etc/passwd     # 印出含 $ 元字符的行

插入與附加文字

[root@mypc /]# sed '/FTP/a\ 456' /etc/passwd      # 在含 FTP 的行「後」插入 456
[root@mypc /]# sed '/FTP/i\ 123' /etc/passwd      # 在含 FTP 的行「前」插入 123
[root@mypc /]# sed '5 a\ 123' /etc/passwd         # 在第 5 行後插入 123
[root@mypc /]# sed '5 i\ "12345"' /etc/passwd     # 在第 5 行前插入 "12345"

其中 a 是 append(附加於後),i 是 insert(插入於前)。

刪除文字

[root@mypc /]# sed '1d' /etc/passwd        # 刪除第 1 行
[root@mypc /]# sed '1,3d' /etc/passwd      # 刪除第 1 至 3 行
[root@mypc /]# sed '/user/d' /etc/passwd   # 刪除含 user 的行

替換文字

替換指令的格式為:

[address[,address]]s/pattern-to-find/replacement-pattern/[g p w n]

[root@mypc /]# sed 's/user/USER/' /etc/passwd      # 換掉第一個 user
[root@mypc /]# sed 's/user/USER/g' /etc/passwd     # 全文替換
[root@mypc /]# sed 's/user/#user/' /etc/passwd     # 加上 # 前綴,達到遮蔽效果
[root@mypc /]# sed 's/user//' /etc/passwd          # 換成空字串
[root@mypc /]# sed 's/user/&11111111111111/' /etc/passwd

最後一行的 & 代表「剛剛比對到的內容本身」,可以拿來重複引用,方便在長字串前後附加內容。

常用一行指令速查

  • 's/\.$//g' 刪除以句點結尾的部分
  • '-e /abcd/d' 刪除包含 a b c d 的行
  • 's/ */ /g' 多個連續空白壓成一個
  • 's/^ *//g' 刪除行首空白
  • '/ $/d' 刪除空行
  • 's/^.//g' 刪除第一個字元
  • 's/COL\(...\)//g' 刪除緊接在 COL 之後的三個字母
  • 's/^\///g' 從路徑中刪掉最前面的斜線
  • 's/ /\t/g' 把空白換成 tab

實務上的一個小建議:用 sed 做過濾時,把複雜需求拆成幾個步驟,邊執行邊驗證結果,比一次寫一大串來得可靠得多。

Copyright © Linux教程網 All Rights Reserved