It really is quite easy to script something like this. For instance, you can source the file with key=value
pairs and then use that to replace the contents of the template. For example:
$ cat template
Hello $name,
someone told me you really like $thing!
$ cat values
name=Bob
thing=chocolate
Your script would then be:
#!/bin/sh
## source the key/value pairs
. "$1"
## Replace them in the template
sed -e "s/\\\$name/$name/g" -e "s/\\\$thing/$thing/g" "$2"
And you run it like this:
$ foo.sh /full/path/to/values template
Hello Bob,
someone told me you really like chocolate!
Of course, that requires you to know the names of the keys in advance. An alternative would be:
#!/bin/sh
tmpFile=$(mktemp)
cp -- "$2" "$tmpFile"
while IFS='=' read -r key value; do
sed -i -e "s/\$$key/$value/g" "$tmpFile"
done < "$1"
cat "$tmpFile"
Another option would be to use eval
to expand the variables. However, this is dangerous since it opens you up to code injection if the values in the file can be dangerous. If that's not an issue for you, try:
#!/bin/sh
## source the key/value pairs
. "$1"
## load the contents of the template
template="$(cat "$2")"
## Now print, but expanding the variables. We need to
## unset IFS to protect the newlines.
IFS=
eval echo \"$template\"