amk
amk

Reputation: 359

BASH: Filling template file with strings

I have a template script with some analysis and the only thing that I need to change in it is a case.

#!/bin/bash
CASE=XXX
... the rest of the script where I use $CASE

I created a list of all my cases, that I saved into file: list.txt. So my list.txt file may contain cases as XXX, YYY, ZZZ.

Now I would run a loop over list.txt content and fill my template_script.sh with a case from the list.txt and then saved the file with a new name - script_CASE.sh

for case in `cat ./list.txt`; 
do
# open template_script.sh
# use somehow the line from template_script.sh (maybe substitute CASE=$case)
# save template_script with a new name script_$case
done

Upvotes: 1

Views: 752

Answers (2)

M. Nejat Aydin
M. Nejat Aydin

Reputation: 10123

In pure bash :

#!/bin/bash

while IFS= read -r casevalue; do
    escaped=${casevalue//\'/\'\\\'\'} # escape single quotes if any
    while IFS= read -r line; do
        if [[ $line = CASE=* ]]; then
            echo "CASE='$escaped'"
        else
            echo "$line"
        fi
    done < template_script.sh > "script_$casevalue"
done < list.txt

Note that saving to "script_$casevalue" may not work if the case contains a / character.

If it is guaranteed that case values (lines in list.txt) needn't to be escaped then using sed is simpler:

while IFS= read -r casevalue; do
    sed -E "s/^CASE=(.*)/CASE=$casevalue/" template_script.sh > "script_$casevalue"
done < list.txt

But this approach is fragile and will fail, for instance, if a case value contains a & character. The pure bash version, I believe, is very robust.

Upvotes: 4

anubhava
anubhava

Reputation: 785008

Converting my comment to answer so that solution is easy to find for future visitors.

You may use this bash script:

while read -r c; do
    sed "s/^CASE=.*/CASE=$c/" template_script.sh > "script_${c}.sh"
done < list.txt

Upvotes: 2

Related Questions