Extending environment variables with sed

I am trying to write a sed command to replace tokens in a file with the values ​​of environment variables, for example:

export my_var=foo
echo 'something {{my_var}} bar' | sed -r "s/\{\{(.*?)\}\}/$\1/g"

In this case, I want to capture the token name ( my_var ), and then replace the value of the environment variable with the same name.

Is it possible? The current text above something $my_var bar, not the something foo barone I want.

I am open to using another tool like awk if this is not possible with sed.

+4
source share
2 answers

After replacing {{my_var}}with $my_varyou need to explicitly send a string for the second round of substitution.

from eval

$ eval echo "$(echo 'something {{my_var}} bar' | sed 's/{{\([^}]\+\)}}/$\1/g')"
something foo bar

or with a subshell

$ echo 'echo something {{my_var}} bar' | sed 's/{{\([^}]\+\)}}/$\1/g' | sh
something foo bar

Perl , ( s/// function e):

$ echo 'something {{my_var}} bar' | perl -pe 's/\{\{(\w+)\}\}/$ENV{$1}/eg' 
something foo bar
+3

, $sign .

export my_var = foo

echo "something {{$ my_var}} bar" | sed -r "s/{{(. *?)}}/$\ 1/g" | sed 's | [$] || g'

:

- foo bar

0

Source: https://habr.com/ru/post/1610943/


All Articles