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)
如何template
用config
文件中的值替换占位符?
我当然可以这样做:
$ . 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)
但是如果有很多配置值,这就变得太麻烦了。我将如何以更通用的方式做到这一点?我想遍历每个占位符并用实际值替换它。
你可以这样做:
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)