Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get variables substituted when I cat a file

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

like image 295
Teresa e Junior Avatar asked Dec 17 '25 16:12

Teresa e Junior


2 Answers

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
like image 94
Jason R Avatar answered Dec 20 '25 18:12

Jason R


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
like image 28
John Zwinck Avatar answered Dec 20 '25 16:12

John Zwinck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!