如何在sed的命令中使用变量? [英] How to use variables in a command in sed?

查看:53
本文介绍了如何在sed的命令中使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 abc.sh:

exec $ROOT/Subsystem/xyz.sh

在 Unix 机器上,如果我打印 echo $HOME 然后我得到 /HOME/COM/FILE.

On a Unix box, if I print echo $HOME then I get /HOME/COM/FILE.

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

I want to replace $ROOT with $HOME using sed.

预期输出:

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

我试过了,但没有得到预期的输出:

I tried, but I'm not getting the expected output:

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,即输出为

it is only replacing first $ROOT, i.e., output is coming as

exec /HOME/COM/FILE/Subsystem/xyz.sh $ROOT/ystem/xyz1.sh

推荐答案

说:

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

注意:

  • 使用双引号以便 shell 扩展变量.
  • 使用不同于 / 的分隔符,因为替换包含 /
  • 对模式中的 $ 进行转义,因为您不想扩展它.
  • 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.

为了替换所有出现的 $ROOT,比如说

In order to replace all occurrences of $ROOT, say

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

这篇关于如何在sed的命令中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆