首页·终端命令

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