Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading