I'd often like to quickly take some data, and apply it to a template in bash.
e.g. imagine doing the following
$ seq 1 2 | eztemplate 'this is a {1} test'
this is a 1 test
this is a 2 test
$ eztemplate 'this is a {1} test' hi 'there now'
this is a hi test
this is a there now test
$ eztemplate /tmp/template /tmp/alphabet | head
this is a a test
of this system a
this is a b test
of this system b
...
I've wrote a very simple bash script that does this, but was considering allowing multiple parameters, like CSV style data, per line of data.
Does something better than my little script already exist, given the following?
- I want it to require only basic unix posix tools, and commonly installed things like perl or awk, but requires no modules be installed additionally by perl, for example
- It can accept multiple columns of data, per line of data in the data file.
- Basically is one bash script that doesn't require installing anything else :D
- A side intent is to allow others that aren't great at bash scripting to have a simple tool to process templates for repeating data
The data and template will vary greatly, but the first example I wanted to do it with was apply 4 ids to a JSON payload
template
{
"tenantId": "{1}",
"key": "some.key",
"value": "some.value"
}
data
my/super/01cbf4e9779649038f0bd753747c8b26
my/test/01cbf4e9779649038f0bd753747c8b26
ez/test/01cbf4e9779649038f0bd753747c8b26
rad/data/df3a47fed39d453f836f9b2196332029
eztemplate
#!/usr/bin/env bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"; PATH="$DIR:$PATH"
function show_help()
{
ME=$(basename "$0")
IT=$(cat <<EOF
replaces vars in a template, one for each line of stdin
e.g.
$ seq 1 2 | $ME 'this is a {1} test'
this is a 1 test
this is a 2 test
$ $ME 'this is a {1} test' hi 'there now'
this is a hi test
this is a there now test
$ $ME /tmp/template /tmp/alphabet
this is a a test
of this system a
this is a b test
of this system b
...
EOF
)
echo "$IT"
echo
exit
}
if [ -z "$1" ]
then
show_help
fi
if [ "$1" = "help" ] || [ "$1" = '?' ] || [ "$1" = "--help" ] || [ "$1" = "h" ]; then
show_help
fi
function process_template(){
DATA=$1
VAR=$2
if [ -f "$DATA" ]; then
DATA=$(cat "$DATA")
fi
echo "$DATA" | sed "s#{1}#$VAR#g"
}
TEMPLATE=$1
if [ -t 0 ]
then
if [ -f "$2" ]; then
# allow first 2 parameters to be files, TEMPLATE and then DATA
DATA_FILE=$2
cat "$DATA_FILE" | while read line
do
process_template "$TEMPLATE" "$line"
done
else
shift;
for line in "$@"
do
process_template "$TEMPLATE" "$line"
done
fi
else
loop over lines from stdin
while IFS= read -r line; do
process_template "$TEMPLATE" "$line"
done
fi