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

it is fine.

But, if I run:

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

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.

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:

  • You may need double quotes, as in sed 's/xxx/'"$PWD"'/'

  • $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"'@'
    

    In addition to Norman Ramsey's answer, I'd like to add that you can double-quote the entire string (which may make the statement more readable and less error prone).

    So if you want to search for 'foo' and replace it with the content of $BAR, you can enclose the sed command in double-quotes.

    sed 's/foo/$BAR/g'
    sed "s/foo/$BAR/g"
    

    In the first, $BAR will not expand correctly while in the second $BAR will expand correctly.


    您可以在替换中使用除“/”之外的其他字符:

    sed "s#$1#$2#g" -i FILE
    
    链接地址: http://www.djcxy.com/p/47122.html

    上一篇: 非贪婪(不情愿)正则表达式在sed中匹配?

    下一篇: 环境变量替代sed