sed 的笔记
1 sed 的指令
sed 的替换指令 有两款。分别如下:
# 第一款
sed -i "s/${regexp_replaced}/${replacement}/g" ${file_path}
# 第二款,带有 ${regexp_previous}
# ${regexp_previous} 可以出现 在 ${regexp_replaced} 的前面或者后面。
sed -i "/${regexp_previous}/s/${regexp_replaced}/${replacement}/g" ${file_path}
2 sed 的 例子
2.1 处理目标
假设 /etc/sysctl.conf
文件上,有如下的 指令。
都替换为 net.ipv4.tcp_sack = 0
。
- 替换前:
net.ipv4.tcp_sack=1
net.ipv4.tcp_sack = 1
net.ipv4.tcp_sack = 1
net.ipv4.tcp_sack = xxxx
- 替换后:
net.ipv4.tcp_sack = 0
net.ipv4.tcp_sack = 0
net.ipv4.tcp_sack = 0
net.ipv4.tcp_sack = 0
2.2 处理方法
可以使用以下两款中的任意一款来进行替换。
# 第一款
sed -i "s/net.ipv4.tcp_sack\s*=\s*\S\+/net.ipv4.tcp_sack = 0/g" /etc/sysctl.conf
# 第二款,带有 ${regexp_previous}
# 可以写出更简短的 指令。
sed -i "/net.ipv4.tcp_sack/s/=\s*\S\+/= 0/g" /etc/sysctl.conf
3 易用脚本
编写了一个脚本。来方便以后使用:
function text_replace ()
{
local ${file_path}=$1
local ${regexp_replaced}=$2
local ${replacement}=$3
local ${regexp_previous}=$4
if [ -z "${regexp_previous}" ]; then
# without regexp_previous
sed -i "s/${regexp_replaced}/${replacement}/g" ${file_path}
else
# with regexp_previous
sed -i "/${regexp_previous}/s/${regexp_replaced}/${replacement}/g" ${file_path}
fi
}
4 notation of regexp in sed
regexp 中,一般知道以下的 notation 就够用了。
notation | description |
---|---|
. | any char |
\d | digit. 1, 2, 3, …, etc. |
\D | not digit |
\s | white space, tab, space, …, etc. |
\S | not white space |
\w | alphabet or digit. 1, 2, 3, …, a, b, c, …, etc. |
\W | not (alphabet or digit). +, -, *, /, …, white space, etc. |
+ | repeat at least one |
* | repeat at least zero |
^ | begin of line |
$ | end of line |
< | begin of word |
> | end of word |
TIPS:
使用 vim 来测试 regexp,是最直观和快速的方法。