我想将一个“模板”文件的输出管道到MySQL中,该文件具有像${dbName}这样的变量。替换这些实例并将输出转储到标准输出的命令行实用程序是什么?

输入文件被认为是安全的,但是可能存在错误的替换定义。执行替换应避免执行意外的代码执行。


当前回答

Sed!

鉴于template.txt:

The number is ${i}
The word is ${word}

我们只能说:

sed -e "s/\${i}/1/" -e "s/\${word}/dog/" template.txt

感谢Jonathan Leffler提供的将多个-e参数传递给同一个sed调用的技巧。

其他回答

使用/bin/sh.创建一个设置变量的小shell脚本,然后使用shell本身解析模板。如下所示(编辑以正确处理换行):

文件template.txt:

the number is ${i}
the word is ${word}

文件script.sh:

#!/bin/sh

#Set variables
i=1
word="dog"

#Read in template one line at the time, and replace variables (more
#natural (and efficient) way, thanks to Jonathan Leffler).
while read line
do
    eval echo "$line"
done < "./template.txt"

输出:

#sh script.sh
the number is 1
the word is dog

创建rendertemplate.sh:

#!/usr/bin/env bash

eval "echo \"$(cat $1)\""

和template.tmpl:

Hello, ${WORLD}
Goodbye, ${CHEESE}

渲染模板:

$ export WORLD=Foo
$ CHEESE=Bar ./rendertemplate.sh template.tmpl 
Hello, Foo
Goodbye, Bar

更新

下面是yottatsa关于类似问题的解决方案,它只替换像$VAR或${VAR}这样的变量,并且是一个简短的一行程序

i=32 word=foo envsubst < template.txt

当然,如果i和word在你的环境中,那么它只是

envsubst < template.txt

在我的Mac上,它看起来是作为gettext和MacGPG2的一部分安装的

旧的答案

这里是一个改进的解决方案从mogsie对类似的问题,我的解决方案不需要你的双引号,mogsie的做,但他是一个一行!

eval "cat <<EOF
$(<template.txt)
EOF
" 2> /dev/null

这两种解决方案的强大之处在于,您只能获得几种正常情况下不会发生的shell扩展类型$((…)),'…',和$(…),虽然反斜杠在这里是一个转义字符,但您不必担心解析有bug,它可以很好地处理多行。

这里有很多选择,但我想把我的扔到堆里。它是基于perl的,只针对形式为${…},将要处理的文件作为参数,并在stdout上输出转换后的文件:

use Env;
Env::import();

while(<>) { $_ =~ s/(\${\w+})/$1/eeg; $text .= $_; }

print "$text";

当然,我不是一个真正的perl人,所以很容易有一个致命的缺陷(对我来说是如此)。

Sed!

鉴于template.txt:

The number is ${i}
The word is ${word}

我们只能说:

sed -e "s/\${i}/1/" -e "s/\${word}/dog/" template.txt

感谢Jonathan Leffler提供的将多个-e参数传递给同一个sed调用的技巧。