Here is a way to do this without sed:
First, a slightly modified template file in which placeholders are bash variables:
blah blah blah blah $PLACEHOLDER_1 blah $PLACEHOLDER_2
And the script:
#! /bin/sh templatefile=output.template outputfile=output.txt PLACEHOLDER_1='string 1' PLACEHOLDER_2='multiline string 2' # DONE: Generate file output.txt from file output.template # using placeholders above. echo "$(eval "echo \"$(cat $templatefile)\"")" > $outputfile
Here's a version showing a template contained in a script, but with a twist. It also demonstrates default values ββthat can also be used in the template file version, plus you can do the math in the template:
#! /bin/sh template='blah blah blah blah $PLACEHOLDER_1 blah ${PLACEHOLDER_2:-"some text"} blah ${PLACEHOLDER_3:-"some lines of text"} and the total is: $((${VAL_1:-0} + ${VAL_2:-0}))' # default operands to zero (or 1) to prevent errors due to unset variables outputfile=output.txt # gears spin, bells ding, values for placeholders are computed PLACEHOLDER_1='string 1' PLACEHOLDER_2='multiline string 2' VAL_1=2 VAL_2=4 unset PLACEHOLDER_3 # so we can trigger one of the defaults # Generate file output.txt from variable $template # using placeholders above. echo "$(eval "echo \"$template\"")" > $outputfile
No sed, no cycles, just hairy nesting and quotes. I am sure that the whole quote will protect you from harmful things in the template file, but I am not going to guarantee this.
Dennis williamson
source share