替换模板中的占位符

Max*_*xim 5 bash configuration text-processing replace variable-substitution

假设我有一个这样的 shell 配置文件config

HOST=localhost
PORT=8080
Run Code Online (Sandbox Code Playgroud)

现在我有一个template这样的模板:

The host is <%= @HOST %>
The port is <%= @PORT %>
Run Code Online (Sandbox Code Playgroud)

如何templateconfig文件中的值替换占位符?

我当然可以这样做:

$ . config
$ sed -e "s/<%= @HOST %>/$HOST/" \
> -e "s/<%= @PORT %>/$PORT/" < template
The host is localhost
The port is 8080
Run Code Online (Sandbox Code Playgroud)

但是如果有很多配置值,这就变得太麻烦了。我将如何以更通用的方式做到这一点?我想遍历每个占位符并用实际值替换它。

Sté*_*las 6

你可以这样做:

eval "cat << __end_of_template__
$(sed 's/[\$`]/\\&/g;s/<%= @\([^ ]*\) %>/${\1}/g' < template)
__end_of_template__"
Run Code Online (Sandbox Code Playgroud)

也就是说,在转义所有,和字符后,将所有 sed 替换为<%= @xxx %>with并让 shell 进行扩展。${xxx}$\`

或者,如果您不能保证template不包含__end_of_template__一行:

eval "cut -c2- << x
$(sed 's/[\$`]/\\&/g;s/<%= @\([^ ]*\) %>/${\1}/g;s/^/y/' < template)
x"
Run Code Online (Sandbox Code Playgroud)

  • +1 做得真好。花了我一点时间来弄清楚更高版本的作用。陈述显而易见的。它使用一个 HEREDOC,其中分隔符是“x”,每行都预先加上一个“y”,以防止只包含“x”的行过早停止 HEREDOC。巧妙:) (2认同)