As an Linux/Unix Engineer i’m spending a huge percentage in developing automatism. Sometimes you need to periodically or automated create config files. I’m using the following script create them in a cool automated way.
- You need a perfect config file e.g. Apache vHost config file
- All occurences of required dynamic variables are replaced with %n% where “n” is numbered streight from 0 to x. If you need the same content more than once you should us the same number again.
- Start the templating script with each value as seperated parameter and pipe the output to the destination file
This is the Script:
#!/bin/bash
# Thomas Spycher - Zero-One - 05.11.2010
# This Script reads in the piped input and goes trough it line for line
# and replaces all occurrences of %n% where n represents an Argument
# passed to the script
# Read in piped input
while IFS= read -r data; do
# Search an Replace line for line
COUNTER=0
for ARG in "$@"
do
VARNAME="%$COUNTER%"
data=${data//$VARNAME/$ARG}
COUNTER=`expr $COUNTER + 1`
done
echo "$data"
done
exit 0 |
For example the creation of a simple Textfile:
Welcome to %0% which lies in %1%.
We in %0% are speaking %2%.
and the execution of the script:
cat template.txt | ./templateScript.sh "Switzerland" "Europe" "German" > switzerland.txt |
Tagged: Automation, Bash