sed中的环境变量替换 [英] Environment variable substitution in sed

查看:189
本文介绍了sed中的环境变量替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我从脚本运行以下命令:

If I run these commands from a script:

#my.sh
PWD=bla
sed 's/xxx/'$PWD'/'
...
$ ./my.sh
xxx
bla

很好.

但是,如果我运行:

#my.sh
sed 's/xxx/'$PWD'/'
...
$ ./my.sh
$ sed: -e expression #1, char 8: Unknown option to `s' 

我在教程中读到,要从shell替换环境变量,您需要停止操作,并在$varname部分中加引号,以使它不被直接替换,这就是我所做的,并且仅当变量有效时才起作用是在紧接之前定义的.

I read in tutorials that to substitute environment variables from shell you need to stop, and 'out quote' the $varname part so that it is not substituted directly, which is what I did, and which works only if the variable is defined immediately before.

我该如何识别$var作为外壳程序中定义的环境变量?

How can I get sed to recognize a $var as an environment variable as it is defined in the shell?

推荐答案

您的两个示例看起来相同,这使问题难以诊断.潜在问题:

Your two examples look identical, which makes problems hard to diagnose. Potential problems:

  1. 您可能需要双引号,如sed 's/xxx/'"$PWD"'/'

$PWD可能包含斜杠,在这种情况下,您需要找到$PWD中包含的字符 not 用作定界符.

$PWD may contain a slash, in which case you need to find a character not contained in $PWD to use as a delimiter.

也许要一次解决这两个问题

To nail both issues at once, perhaps

sed 's@xxx@'"$PWD"'@'

这篇关于sed中的环境变量替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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