Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing environment variables in a properties file

Tags:

linux

In Linux, say I have the following file (e.g. conf.properties):

HOST_URL=http://$HOSTNAME STD_CONFIG=http://$HOSTNAME/config USER_CONFIG=http://$HOSTNAME/config/$unconfigured 

I want to create another file with all the environment variables replaced...e.g. say the environment variable $HOSTNAME is 'myhost' and $unconfigured is not set, a script should produce the following output:

HOST_URL=http://myhost STD_CONFIG=http://myhost/config USER_CONFIG=http://myhost/config/ 

I was thinking this could be done in a simple one-liner with some sort of sed/awk magic, but I'm no expert and my searches have been in vein, so appreciate any help.

Edit:

I should mention that the file can really be any format text file, for example xml. I just want to replace anything that looks like an env variable with whatever is currently set in the environment.

like image 528
Andy Whitfield Avatar asked Mar 11 '11 14:03

Andy Whitfield


1 Answers

This is what envsubst is for.

echo 'Hello $USER' Hello $USER echo 'Hello $USER' | envsubst Hello malvineous 

You would probably use it more like this though:

envsubst < input.txt > output.txt 

envsubst seems to be part of GNU gettext.

like image 68
Malvineous Avatar answered Sep 20 '22 05:09

Malvineous