1

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
3
  • Use: while read -r c; do sed "s/^CASE=.*/CASE=$c/" template_script.sh > "script_{c).sh"; done < list.txt Commented Jul 10, 2020 at 8:05
  • You know that you can export variables with export CASE=xxx and that this variables are available in your script? Rewriting code is in most cases a silly idea. If you really need templates, you should consider an appropriate tool like m4. Commented Jul 10, 2020 at 9:23
  • @anubhava thanks for nice piece of code - there is one small mistake, but this works perfectly for me: while read -r c; do sed "s/^CASE=.*/CASE=$c/" template_script.sh > "script_${c}.sh"; done < list.txt Commented Jul 10, 2020 at 9:35

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.