如何在 sed 中使用命令中的变量?

我有 abc.sh:

exec $ROOT/Subsystem/xyz.sh

在 Unix 机器上,如果我打印 echo $HOME,那么我得到 /HOME/COM/FILE

我想用 sed 将 $ROOT替换为 $HOME

预期产出:

exec /HOME/COM/FILE/Subsystem/xyz.sh

我试过了,但是没有得到预期的结果:

sed  's/$ROOT/"${HOME}"/g' abc.sh > abc.sh.1

附加:

如果我有 abc.sh

exec $ROOT/Subsystem/xyz.sh $ROOT/ystem/xyz1.sh

然后

sed "s|\$INSTALLROOT/|${INSTALLROOT}|" abc.sh

它只是替换第一个 $ROOT,也就是说,输出是作为

exec /HOME/COM/FILE/Subsystem/xyz.sh $ROOT/ystem/xyz1.sh
166119 次浏览

Say:

sed "s|\$ROOT|${HOME}|" abc.sh

Note:

  • Use double quotes so that the shell would expand variables.
  • Use a separator different than / since the replacement contains /
  • Escape the $ in the pattern since you don't want to expand it.

EDIT: In order to replace all occurrences of $ROOT, say

sed "s|\$ROOT|${HOME}|g" abc.sh

This might work for you:

sed 's|$ROOT|'"${HOME}"'|g' abc.sh > abc.sh.1
This may also can help


input="inputtext"
output="outputtext"
sed "s/$input/${output}/" inputfile > outputfile

The safe for a special chars workaround from https://www.baeldung.com/linux/sed-substitution-variables with improvement for \ char:

#!/bin/bash
to="/foo\\bar#baz"
echo "str %FROM% str" | sed "s#%FROM%#$(echo ${to//\\/\\\\} | sed 's/#/\\#/g')#g"