bash - 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.sh
case
list.txt
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
解决方案
在纯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
版本非常强大。
推荐阅读
- python - 按列对完整的熊猫数据框进行排序,同时保留序列顺序
- r - 在 Shiny 应用程序中更改 shinyWidget 的 switchInput 默认颜色
- elasticsearch - 在 FileBeat 上发送之前排除字段
- javascript - 如果满足条件后语句不停止
- flutter - 如何在 BottomNavigationBar Flutter 中重新加载状态 onTap
- anylogic - AnyLogic Simulation NullPointerException 在版本 8.7.2&8.7.0 上的 Descrete 事件执行期间
- docker - 我们如何使用 docker buildkit 从中间层运行?
- quicksort - 快速排序中的比较次数
- python - numpy fft中的意外幅度
- php - 如何在 XML 文档中根据子元素的值使用 PHP 删除特定元素