Linux 用法
sed 可以将文件中的字符串进行替换,如将 settings.py 文件中的 DEBUG = True 替换为 DEBUG = False
sed -i 's/DEBUG = True/DEBUG = False/g' ./settings.py
macOS 用法
以上用法在 macOS 中使用会报错,还需要在 -i 参数后添加备份后缀。sed 替换前会将原文件进行备份,如果不需要备份,则将 '.copy' 替换为 ''
sed -i '.copy' 's/DEBUG = True/DEBUG = False/g' ./settings.py
替换引号
在 shell 中, 使用 sed 进行替换的时候,因为替换命令本身就是在引号中的,所以书写的时候,就需要注意书写的格式,这里总结几种写法。简单的是 echo "this is''' test\" string" | sed $'s/\'//g'
# shell中使用sed替换单引号
echo "this is''' test\" string" | sed $'s/\'//g'
this is test" string
# shell中使用sed替换双引号
echo "this is''' test\" string" | sed $'s/\"//g'
this is''' test string
# shell中使用sed替换双引号和单引号
echo "this is''' test\" string" | sed "s/[\'\"]//g"
this is test string
# shell中使用sed替换双引号和单引号
echo "this is''' test\" string" | sed "s/[\x27\x22]//g"
this is test string
# shell中使用sed替换双引号和单引号
echo "this is''' test\" string" | sed $'s/[\'\"]//g'
this is test string