sed中的环境变量替换 [英] Environment variable substitution in 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:
-
您可能需要双引号,如
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屋!