我已经成功地使用下面的sed命令来搜索/替换Linux中的文本:

sed -i 's/old_link/new_link/g' *

然而,当我在Mac OS X上尝试它时,我得到:

“命令c期望\后面跟着文本”

我以为我的Mac运行一个正常的BASH shell。有什么事吗?

编辑:

根据@High Performance的说法,这是因为Mac sed是不同的(BSD)风格,因此我的问题是如何在BSD sed中复制这个命令?

编辑:

下面是一个实际的例子:

sed -i 's/hello/gbye/g' *

当前回答

下面是bash脚本中的一个选项:

#!/bin/bash

GO_OS=${GO_OS:-"linux"}

function detect_os {
    # Detect the OS name
    case "$(uname -s)" in
      Darwin)
        host_os=darwin
        ;;
      Linux)
        host_os=linux
        ;;
      *)
        echo "Unsupported host OS. Must be Linux or Mac OS X." >&2
        exit 1
        ;;
    esac

   GO_OS="${host_os}"
}

detect_os

if [ "${GO_OS}" == "darwin" ]; then
    sed -i '' -e ...
else
    sed -i -e ...
fi

其他回答

下面是bash脚本中的一个选项:

#!/bin/bash

GO_OS=${GO_OS:-"linux"}

function detect_os {
    # Detect the OS name
    case "$(uname -s)" in
      Darwin)
        host_os=darwin
        ;;
      Linux)
        host_os=linux
        ;;
      *)
        echo "Unsupported host OS. Must be Linux or Mac OS X." >&2
        exit 1
        ;;
    esac

   GO_OS="${host_os}"
}

detect_os

if [ "${GO_OS}" == "darwin" ]; then
    sed -i '' -e ...
else
    sed -i -e ...
fi
sed -ie 's/old_link/new_link/g' *

可以在BSD和Linux上使用gnu sed

在Mac中遇到了同样的问题,并使用brew解决了它:

brew install gnu-sed

使用as

gsed SED_COMMAND

你也可以将sed作为别名设置为gsed(如果你想):

alias sed=gsed

或者,您可以在Mac中安装sed的GNU版本,称为gsed,并使用标准Linux语法使用它。

为此,通过运行sudo port install gsed,使用端口安装gsed(如果没有端口,可以在http://www.macports.org/上获取)。然后执行sed -i 's/old_link/new_link/g' *

我相信在OS X上使用-i时,需要备份文件的扩展名。试一试:

sed -i .bak 's/hello/gbye/g' *

使用GNU sed扩展是可选的。