bash - 一次性填充文件中的占位符

标签 bash replace sed awk textutils

我有一个带有占位符字符串的框架文本文件:

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/

相关文章:

bash - 如何在 Bash 中编写花式缩进的多行大括号扩展?

javascript - 在 javascript 中使用 string.replace() 来更改文本区域的内容

java - 如果字符是 0 到 8 之间的数字,则将其增加 1(其他字符不变)

bash - 无法使用sed更新docker compose文件中的版本标签

regex - grep : Regex for IP doesnt match

linux - 在 shell 脚本中列出文件

python - 使用 Django 运行 bash 脚本

iOS:将对象从 oldArray 复制到 newArray

bash - 在 bash 中使用 gnu parallel 和 cat 时删除多个文件扩展名

linux - 如何替换两点之间的所有行并将其替换为sed中的一些文本