sed
文字處理
用法
sed -i 's/[old]/[new]/g' [file]逐行改寫文字,最常用 s/old/new/;原地修改的 -i 在 GNU 和 BSD 上寫法不同,結尾不加 g 只會替換每行的第一處。
常用選項
| 選項 | 含義 |
|---|---|
| s/a/b/g | Replace a with b; without the trailing g only the first per line |
| -i | Edit in place. GNU takes -i alone, BSD and macOS need -i "" |
| -E | Extended regex; BSD also accepts -r for GNU compatibility |
| -n | Print nothing unless a command says to, usually with p |
| -e | Add another expression to the script |
| -f | Read the script from a file |
範例
sed -i 's/foo/bar/g' file.txtReplaces every foo in place (GNU).
sed -i '' 's/foo/bar/g' file.txtThe same on macOS, with the empty argument.
sed -n '10,20p' file.txtPrints 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