我想将一个“模板”文件的输出管道到MySQL中,该文件具有像${dbName}这样的变量。替换这些实例并将输出转储到标准输出的命令行实用程序是什么?
输入文件被认为是安全的,但是可能存在错误的替换定义。执行替换应避免执行意外的代码执行。
我想将一个“模板”文件的输出管道到MySQL中,该文件具有像${dbName}这样的变量。替换这些实例并将输出转储到标准输出的命令行实用程序是什么?
输入文件被认为是安全的,但是可能存在错误的替换定义。执行替换应避免执行意外的代码执行。
当前回答
下面是一种让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是指定的环境变量。
其他回答
下面是一种让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是指定的环境变量。
这里有很多选择,但我想把我的扔到堆里。它是基于perl的,只针对形式为${…},将要处理的文件作为参数,并在stdout上输出转换后的文件:
use Env;
Env::import();
while(<>) { $_ =~ s/(\${\w+})/$1/eeg; $text .= $_; }
print "$text";
当然,我不是一个真正的perl人,所以很容易有一个致命的缺陷(对我来说是如此)。
使用/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
我在想同样的事情时发现了这条线索。这启发了我(注意反节拍)
$ echo $MYTEST
pass!
$ cat FILE
hello $MYTEST world
$ eval echo `cat FILE`
hello pass! world
这是我的解决方案与perl基于以前的答案,替换环境变量:
perl -p -e 's/\$\{(\w+)\}/(exists $ENV{$1}?$ENV{$1}:"missing variable $1")/eg' < infile > outfile