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