我在 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/