我有一个带有占位符字符串的框架文本文件:
blah blah blah
blah $PLACEHOLDER_1$
blah
$PLACEHOLDER_2$
等等。占位符的具体“形式”并不重要——我可以将它们更改为最适合具体实现的形式。
我有一个 bash 脚本,其中我知道占位符的值,我需要生成一个新文件,用值替换占位符。
#! /bin/sh
PLACEHOLDER_1 = 'string 1'
PLACEHOLDER_2 = 'multiline
string
2'
# TODO: Generate file output.txt from file output.template
# using placeholders above.
我可以使用 sed 多次执行此操作,但这并不好玩。我不想使用 Perl。我只想使用 textutils 和 bash 本身。
一次性完成我想做的事情的最佳方法是什么?
最佳答案
这里有一个不用 sed 的方法:
首先,一个稍微修改过的模板文件,其中占位符是 bash 变量:
blah blah blah
blah $PLACEHOLDER_1
blah
$PLACEHOLDER_2
和脚本:
#! /bin/sh
templatefile=output.template
outputfile=output.txt
PLACEHOLDER_1='string 1'
PLACEHOLDER_2='multiline
string
2'
# DONE: Generate file output.txt from file output.template
# using placeholders above.
echo "$(eval "echo \"$(cat $templatefile)\"")" > $outputfile
这是一个演示脚本中包含的模板的版本,但有所不同。它还演示了默认值,这些值也可以在模板文件版本中使用,而且您可以在模板中进行数学运算:
#! /bin/sh
template='blah blah blah
blah $PLACEHOLDER_1
blah
${PLACEHOLDER_2:-"some text"} blah ${PLACEHOLDER_3:-"some
lines
of
text"} and the total is: $((${VAL_1:-0} + ${VAL_2:-0}))'
# default operands to zero (or 1) to prevent errors due to unset variables
outputfile=output.txt
# gears spin, bells ding, values for placeholders are computed
PLACEHOLDER_1='string 1'
PLACEHOLDER_2='multiline
string
2'
VAL_1=2
VAL_2=4
unset PLACEHOLDER_3 # so we can trigger one of the defaults
# Generate file output.txt from variable $template
# using placeholders above.
echo "$(eval "echo \"$template\"")" > $outputfile
没有 sed,没有循环,只有毛茸茸的嵌套和引号。我很确定所有引用都可以保护您免受模板文件中恶意内容的侵害,但我不保证这一点。
关于bash - 一次性填充文件中的占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/407279/