首页 > 解决方案 > BASH:用字符串填充模板文件

问题描述

我有一个带有一些分析的模板脚本,唯一需要更改的是case.

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

我创建了一个我所有的列表cases,我保存到文件中:list.txt. 所以我的 list.txt 文件可能包含 XXX、YYY、ZZZ 等案例。

现在我将在内容上运行一个循环并用fromlist.txt填充我,然后用新名称保存文件 -template_script.shcaselist.txtscript_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

标签: bash

解决方案


在纯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

/请注意,如果大小写包含字符,则保存到“script_$casevalue”可能不起作用。

如果保证不需要对 case 值(list.txt 中的行)进行转义,则使用sed更简单:

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

但是这种方法很脆弱,并且会失败,例如,如果一个 case 值包含一个&字符。我相信纯bash版本非常强大。


推荐阅读