我想将一个“模板”文件的输出管道到MySQL中,该文件具有像${dbName}这样的变量。替换这些实例并将输出转储到标准输出的命令行实用程序是什么?
输入文件被认为是安全的,但是可能存在错误的替换定义。执行替换应避免执行意外的代码执行。
我想将一个“模板”文件的输出管道到MySQL中,该文件具有像${dbName}这样的变量。替换这些实例并将输出转储到标准输出的命令行实用程序是什么?
输入文件被认为是安全的,但是可能存在错误的替换定义。执行替换应避免执行意外的代码执行。
当前回答
使用/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
其他回答
在地方perl编辑潜在的多个文件,与备份。
perl -e 's/\$\{([^}]+)\}/defined $ENV{$1} ? $ENV{$1} : ""/eg' \
-i.orig \
-p config/test/*
使用/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
我建议使用像Sigil这样的东西: https://github.com/gliderlabs/sigil
它被编译成一个二进制文件,所以在系统上安装它非常容易。
然后你可以像下面这样简单的一行代码:
cat my-file.conf.template | sigil -p $(env) > my-file.conf
这比eval更安全,比使用regex或sed更容易
如果您愿意使用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
鉴于最近的兴趣,我又在考虑这个问题,我认为我最初想到的工具是m4,用于autotools的宏处理器。所以不是我最初指定的变量,你会使用:
$echo 'I am a DBNAME' | m4 -DDBNAME="database name"