首頁·終端機命令

sed

文字處理

用法

sed -i 's/[old]/[new]/g' [file]

逐行改寫文字,最常用 s/old/new/;原地修改的 -i 在 GNU 和 BSD 上寫法不同,結尾不加 g 只會替換每行的第一處。

常用選項

選項含義
s/a/b/gReplace a with b; without the trailing g only the first per line
-iEdit in place. GNU takes -i alone, BSD and macOS need -i ""
-EExtended regex; BSD also accepts -r for GNU compatibility
-nPrint nothing unless a command says to, usually with p
-eAdd another expression to the script
-fRead the script from a file

範例

sed -i 's/foo/bar/g' file.txt

Replaces every foo in place (GNU).

sed -i '' 's/foo/bar/g' file.txt

The same on macOS, with the empty argument.

sed -n '10,20p' file.txt

Prints only lines 10 to 20.

它們本來就是用管線串起來用的。串三條往往比讓一條命令做完所有事更短。

怎麼看

  • 方括號 [ ] 表示這部分可以不寫。
  • 省略號 … 表示可以寫多個。
  • 選項區分大小寫——有些命令裡 -r 和 -R 不是一回事。

常見問題

Q. sed 是做什麼的?

逐行改寫文字,最常用 s/old/new/;原地修改的 -i 在 GNU 和 BSD 上寫法不同,結尾不加 g 只會替換每行的第一處。

Q. 怎麼寫?

sed -i 's/[old]/[new]/g' [file] —— 方括號表示可以省略的部分。

Q. 值得記的選項有幾個?

這裡列了 6 個,完整列表在 man sed。這條命令屬於文字處理。

相關命令

man 手冊: man sed