我正在尝试编写一个Bash脚本,用于将文件中所有占位符的出现替换为同名的环境变量。例如,如果我有一个如下所示的文件...
This is an {{VAR1}} {{VAR2}}.
It should work across multiple lines in this {{VAR2}}.
我有以下环境变量设置:
VAR1='example'
VAR2='file'
在运行脚本后,我应该得到以下输出结果:
This is an example file.
It should work across multiple lines in this file.
我相信可以使用awk/sed找到解决方案,但目前为止,最接近的方法无法处理一行中有多个变量的情况。以下是我迄今为止的尝试:
cat example.txt | grep -o '{{.*}}' > temp
while read placeholder; do
varName=$(echo "$placeholder" | tr -d '{}')
value="${!varName}"
sed -i "s/$placeholder/$value/g" "$file"
done < temp
rm -rf temp
m4
宏处理器? - Mark Setchell