2

I am interested if there is a UNIX tool which replaces occurences of $VAR or ${VAR} (for all existing variables in the env, not just one) with the actual values of environment variables. This replacment is in a plain text file, not a bash script; a "poor man's template engine" of sort.

I know I can do

(echo 'echo -n "'; sed -e "s/\"/\"'\"'\"/g" infile; echo '"') | sh -s >outfile

(I do, in fact), but if there is a well-known tool for that, I'd rather use it instead of clever sh tricks.

EDIT: @glennjackman suggest use of eval, so the line is shorter and without subshell:

eval echo -n \""`sed -e 's/"/\\\\\\\"/g' infile`"\" >outfile

which is pretty short (though not a dedicated tool, but good enough if there is none).

  • I have not tried this (hence the comment), but with a simple script it should be possible to use `bash -x infile 2> outfile`, which will do all shell expansions. – cdarke Nov 14 '12 at 19:23
  • @cdarke: I did not know `bash -x`, but I wonder if it would work in generic replacement in a text file, not in a bash script... –  Nov 14 '12 at 20:30
  • @glennjackman: `eval` may help me in fact with the trick above to ditch subsscript (thus, no need to `export`), thanks. But alone, it would try to evaluate the contents, which is not a script, but a normal text file. What I look for is "poor man's template engine". :-) –  Nov 14 '12 at 20:33
  • @glennjackman Maybe make your suggestion an answer, I will pick if nothing shorter appears. –  Nov 14 '12 at 20:49
  • @herby: no, it would not be generic. It will also depend exactly what type of shell expansions on variables you need to support. – cdarke Nov 16 '12 at 13:30

1 Answers1

1

An example with eval

tmpl='Hello $x'
x=world
eval str=\"$tmpl\"
echo $str   # => Hello world

If your template has embedded double quotes, this will get messy.

glenn jackman
  • 207,528
  • 33
  • 187
  • 305
  • I already solved the embedded double quotes in the EDIT part, but it needed 7 backslashes :-) –  Nov 15 '12 at 12:26