Is it possible, in a clean way to get the variable values when I cat a file, instead of the variable names, as written in the file. It's hard to explain, but here goes a simple example:
$ cat <<EOF
$HOME
EOF
/home/myself
cat returns /home/myself because it is already expanded by the shell.
$ echo \$HOME >/tmp/home
$ cat /tmp/home
$HOME
cat simply reads the file, I want $HOME to be expanded here somehow by cat, because the file will contain variable names (not like HOME=/home/myself)
My question is if this is possible somehow, otherwise I will have to write some dirty code.
EDIT: they are big xml files containing
<checkbox active="$value">
true or false
I recently found a way to do this with envsubst:
export MYNAME="Jason"
echo '{ "status": 200, "message": { "name": "$MYNAME" } }' > my.json.template
cat my.json.template
# outputs { "status": 200, "message": { "name": "$MYNAME" } }
cat my.json.template | envsubst
# outputs { "status": 200, "message": { "name": "Jason" } }
If you don't have the envsubst you can install it on debian distros with:
apt-get install gettext-base
This would be trivial to attempt in Python, and see if that works for you. You could use the re.sub function to replace all occurrences of some pattern like "\$\w+" by calling a function which does the transformation (rather than a specific string to replace it with). And for the replacement function you could use os.getenv(), which of course takes a variable name and returns its value.
Edit: Here's a complete Python script that does the above:
#!/usr/bin/python
import fileinput
import os
import re
def transform(match):
return os.getenv(match.group(1)) # replace the "capture" to omit $
for line in fileinput.input(): # reads from stdin or from a file in argv
print re.sub('\$(\w+)', transform, line), # comma to omit newline
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With