为什么sed不识别\字符?

时间:2014-10-07 15:01:34

标签: 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

但我得到同样的错误。

谢谢。

1 个答案:

答案 0 :(得分:1)

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

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

 -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