0

Thanks to Elias Probst's answer here, I'm using this to replace environment variables in a text file:

TARGET_FILE=/etc/apache2/apache2.conf;
for VARNAME in $(grep -P -o -e '\$\{\S+\}' ${TARGET_FILE} | sed -e 's|^\${||g' -e 's|}$||g' | sort -u);
  do sed -i "s|\${$(echo $VARNAME)}|${!VARNAME}|g" ${TARGET_FILE};
done

I'd like this to be something that I could alias and pipe the templated file into and be able to have the replaced file written to standard out. I can imagine how to do this with a temporary file (copy the template to a temp file, run sed and let it replace in place, cat out the temp file), but I'd prefer to avoid that.

Any hints? Thank you!

Community
  • 1
  • 1
colemickens
  • 119
  • 2
  • 11
  • Just remove `-i` and `sed` will write to standard output. Remove `${TARGET_FILE}` from the `sed` command and it will read standard input. Put those two together and you have a solution. The only problem with that is that you can't then use the file in the `grep` command since you only get to read the input stream once (by default though you could clone the fd to work around that if you really wanted to but operating on a given file and writing to standard output is likely simpler and easier). – Etan Reisner Apr 24 '15 at 20:27
  • Etan, will passing from stdout/stdin work even with sed in a for loop like that? I couldn't quite reason through it in my head. – colemickens Apr 24 '15 at 20:36
  • Good point, no, it won't work for the same reason. You'd need to keep copying the original fd for that to work I believe. – Etan Reisner Apr 24 '15 at 20:42
  • Personally I would replace that whole mess with `awk` or `perl`/etc. or anything other than `sed` which can do the matching and dynamically access environment variables. Because then it could be a stream filter. – Etan Reisner Apr 24 '15 at 20:43
  • The answers [here](http://stackoverflow.com/questions/2914220/bash-templating-how-to-build-configuration-files-from-templates-with-bash/2916159#2916159) are better and includes a pipable perl version – that other guy Apr 24 '15 at 21:26

0 Answers0