shell - 在 OS X 上使用 sed 和 shell 变量进行路径替换

标签 shell sed string-interpolation

我在 Mac OS X 上使用 sed 进行就地替换。

基本上我有这个:

#!/bin/sh -e
PREFIX="$1"

sed -i bak -e 's|OCAMLDIR|"${PREFIX}"|g' ocamloptrev

哪里PREFIX是一条路径,因此我使用的是 | .

不幸的是,文件路径中的变量没有按照我的预期进行评估,我最终得到:
OCAMLC="${PREFIX}"/bin/ocamlopt

我怎样才能得到对${PREFIX}的正确评价进sed命令?

最佳答案

尝试这个:

#!/bin/sh -e
PREFIX="$1"

sed -i bak -e 's|OCAMLDIR|'"${PREFIX}"'|g' ocamloptrev
您基本上在做的是“退出”/离开单引号字符串,进入双引号字符串,解释双引号内的变量,然后再次输入单引号。
在这个简单的例子中,我们也可以只使用双引号,它允许解释变量:
#!/bin/sh -e
PREFIX="$1"

sed -i bak -e "s|OCAMLDIR|${PREFIX}|g" ocamloptrev
如果您尝试在单引号内使用双引号 ( "" ),它们也不会被解释。 This part of the Bash manual更详细地解释了这一点。

3.1.2.2 Single Quotes

Enclosing characters in single quotes (‘'’) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

3.1.2.3 Double Quotes

Enclosing characters in double quotes (‘"’) preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). ...

关于shell - 在 OS X 上使用 sed 和 shell 变量进行路径替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34969408/

相关文章:

regex - 如何替换文件名中的数字但从中减去 1?

amazon-web-services - 为什么我需要 AWS CloudFormation 中的额外元素来插入变量

python - 如何删除与第一行一起注释掉的行?

c# - 在 C# 6 字符串插值中对 "{"进行转义

scala - 为什么不能在字符串插值中使用 _ ?

linux - 如何将密码作为参数传递给 shell 脚本

linux - 从 shell 脚本锁定 ubuntu

iphone - shell脚本中的xcode构建版本号

linux - 内部脚本失败后清理外部 Bash 脚本

bash - 如何过滤掉./gradle project:dependencies命令的特定部分? (版本2)