为什么 sed 无法识别 \ 字符?

  • 本文关键字:识别 字符 sed unix sed
  • 更新时间 :
  • 英文 :


我在一个文件中有很多想要使用sed删除的\。这是我的命令:

sed -i.bak 's/\//g' myFile

我得到以下错误:

sed: 1: "i.bak": command i expects  followed by text.

它不应该起作用吗。我试过了:

sed -i.bak 's/\//g' myFile

但我也犯了同样的错误。

谢谢。

当您在OS X上使用sed时,并且当您想使用-i标志就地更改文件时,则需要指定保存该文件备份的扩展名。

查看关于-i标志的man sed部分:

 -i extension
         Edit files in-place, saving backups with the specified extension.  If a zero-length extension is
         given, no backup will be saved.  It is not recommended to give a zero-length extension when in-
         place editing files, as you risk corruption or partial content in situations where disk space is
         exhausted, etc.

因此,正确的命令是:

sed -i "bak" "s/\//g" myFile

如果你不想制作备份文件,你可以这样写:

sed -i "" "s/\//g" myFile

如果你想让你的脚本平台独立,你可以检查$OSTYPE环境变量:

if [[ "$OSTYPE" == "darwin"* ]]; then
  sed -i "" "s/\//g" myFile
else
  sed -i "s/\//g" myFile
fi

最新更新