Home > database >  Sed construct populate list of keys with the environment value of that key
Sed construct populate list of keys with the environment value of that key

Time:11-23

I have a list of keys in a FILE:

FOO
BAR
BAZ

I am trying to construct a sed command to replace each line with:

FOO=$FOO
BAR=$BAR
BAZ=$BAZ

Where the right hand side is the value of the env variable with that name. For example, setting the environment variables:

export FOO=1
export BAR=2
export BAZ=3

After running sed, the FILE should be:

FOO=1
BAR=2
BAZ=3

I have tried these:

  • sed -i 's/^\(.*\)$/\1=$\1/g'
  • sed -i "s/^\(.*\)$/\1=$\1/g"
  • sed -i s/^\(.*\)$/\1="$\1"/g'

And a few other variations. The issue is clearly in how the capture group is escaped, but I don't know how to fix it.

CodePudding user response:

You can't access environment variables in sed in the ways you are trying but it is quite simple with awk:

awk '{ print $0 in ENVIRON ? $0"="ENVIRON[$0] : $0 } FILE >FILE.new \
&& mv FILE.new FILE || { echo oops; rm FILE.new; }
  • Related