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

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


当前回答

对我来说,这是最简单和最强大的解决方案,你甚至可以使用相同的命令eval echo "$(<template.txt)包含其他模板:

带有嵌套模板的示例

创建模板文件,变量是常规bash语法${VARIABLE_NAME}或$VARIABLE_NAME

你必须在模板中用\转义特殊字符,否则它们将被eval解释。

template.txt

Hello ${name}!
eval echo $(<nested-template.txt)

nested-template.txt

Nice to have you here ${name} :\)

创建源文件

template.source

declare name=royman 

解析模板

source template.source && eval echo "$(<template.txt)"

输出

Hello royman!
Nice to have you here royman :)

其他回答

在地方perl编辑潜在的多个文件,与备份。

  perl -e 's/\$\{([^}]+)\}/defined $ENV{$1} ? $ENV{$1} : ""/eg' \
    -i.orig \
    -p config/test/*

这是我的解决方案与perl基于以前的答案,替换环境变量:

perl -p -e 's/\$\{(\w+)\}/(exists $ENV{$1}?$ENV{$1}:"missing variable $1")/eg' < infile > outfile

如果您愿意使用Perl,这就是我的建议。尽管可能有一些sed和/或AWK专家知道如何更容易地做到这一点。如果您有一个比dbName更复杂的映射可供替换,那么您可以很容易地扩展它,但是此时您也可以将它放入标准Perl脚本中。

perl -p -e 's/\$\{dbName\}/testdb/s' yourfile | mysql

一个简短的Perl脚本来做一些稍微复杂的事情(处理多个键):

#!/usr/bin/env perl
my %replace = ( 'dbName' => 'testdb', 'somethingElse' => 'fooBar' );
undef $/;
my $buf = <STDIN>;
$buf =~ s/\$\{$_\}/$replace{$_}/g for keys %replace;
print $buf;

如果你将上面的脚本命名为replace-script,那么它可以像下面这样使用:

replace-script < yourfile | mysql

下面是一种让shell为您执行替换的方法,就像在双引号之间输入文件的内容一样。

以包含内容的template.txt为例:

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

下面的代码行将使shell插入template.txt的内容并将结果写入标准输出。

i='1' word='dog' sh -c 'echo "'"$(cat template.txt)"'"'

解释:

I和word作为环境变量传递给sh的执行。 Sh执行传入的字符串的内容。 相邻的字符串变成一个字符串,这个字符串就是: “echo”+“$(cat template.txt)”+ " ' 由于替换在"之间,"$(cat template.txt)"成为cat template.txt的输出。 因此sh -c执行的命令变成: echo“数字是${i}\n字是${word}”, 其中I和word是指定的环境变量。

使用/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