读取文本文件,以行为单位处理并执行操作
参数
sed [OPTION]... {script-only-if-no-other-script} [input-file]
OPTIONS:
* -n : silent
* -i : edit file in place
* -e script
* -r,-E : Use extended regex syntax (等效于 grep 的 -E)
示例
替换配置文件内容
替换配置文件 config.yaml 里的 "interface-name: foobar" 为 "interface-name: wan" : (shell)
#!/bin/sh
WAN=wan
sed -i -e "/^interface-name:\s*/s:\:.*$:\: ${WAN}:" config.yaml
注意每次执行都会写入文件,即使当前内容已经是 interface-name: wan。如果要仅在当前配置不同时修改,加上 if 判断:
#!/bin/sh
WAN=wan
if ! grep -E "^interface-name:\s+${WAN}\s*" config.yaml
then
fi
输出正则匹配的子分组
sed -n "s/^.*foobar\s*\(\S*\).*$/\1/p"
-n suppress printing
s substitute
^.* anything before foobar
foobar initial search match
\s* any white space character (space)
\( start capture group
\S* capture any non-white space character (word)
\) end capture group
.*$ anything after the capture group
\1 substitute everything with the 1st capture group
p print it
sed in shell
字符串转义
In the shell, everything between single quotes is interpreted literally, except for single quotes themselves. You can effectively have a single quote between single quotes by writing '\'' (close single quote, one literal single quote, open single quote).
sed / grep 默认使用 basic regular expressions。这种模式下 "(){}+?|" 字符默认为 literal,前面必须加上 "\" 才表示特殊含义。使用 -E 参数让 sed / grep 使用扩展正则模式。
详细信息。