我想将一个“模板”文件的输出管道到MySQL中,该文件具有像${dbName}这样的变量。替换这些实例并将输出转储到标准输出的命令行实用程序是什么?
输入文件被认为是安全的,但是可能存在错误的替换定义。执行替换应避免执行意外的代码执行。
我想将一个“模板”文件的输出管道到MySQL中,该文件具有像${dbName}这样的变量。替换这些实例并将输出转储到标准输出的命令行实用程序是什么?
输入文件被认为是安全的,但是可能存在错误的替换定义。执行替换应避免执行意外的代码执行。
当前回答
我在想同样的事情时发现了这条线索。这启发了我(注意反节拍)
$ echo $MYTEST
pass!
$ cat FILE
hello $MYTEST world
$ eval echo `cat FILE`
hello pass! world
其他回答
创建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
这是我的解决方案与perl基于以前的答案,替换环境变量:
perl -p -e 's/\$\{(\w+)\}/(exists $ENV{$1}?$ENV{$1}:"missing variable $1")/eg' < infile > outfile
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调用的技巧。
如果可以控制配置文件格式,则可以在bash中完成。您只需要源(“。”)配置文件,而不需要对其进行子shell。这确保了变量是在当前shell的上下文中创建的(并且继续存在),而不是在子shell中创建的(当子shell退出时,变量消失)。
$ cat config.data
export parm_jdbc=jdbc:db2://box7.co.uk:5000/INSTA
export parm_user=pax
export parm_pwd=never_you_mind
$ cat go.bash
. config.data
echo "JDBC string is " $parm_jdbc
echo "Username is " $parm_user
echo "Password is " $parm_pwd
$ bash go.bash
JDBC string is jdbc:db2://box7.co.uk:5000/INSTA
Username is pax
Password is never_you_mind
如果你的配置文件不是shell脚本,你可以在执行之前“编译”它(编译取决于你的输入格式)。
$ cat config.data
parm_jdbc=jdbc:db2://box7.co.uk:5000/INSTA # JDBC URL
parm_user=pax # user name
parm_pwd=never_you_mind # password
$ cat go.bash
cat config.data
| sed 's/#.*$//'
| sed 's/[ \t]*$//'
| sed 's/^[ \t]*//'
| grep -v '^$'
| sed 's/^/export '
>config.data-compiled
. config.data-compiled
echo "JDBC string is " $parm_jdbc
echo "Username is " $parm_user
echo "Password is " $parm_pwd
$ bash go.bash
JDBC string is jdbc:db2://box7.co.uk:5000/INSTA
Username is pax
Password is never_you_mind
在你的具体情况下,你可以使用如下语句:
$ cat config.data
export p_p1=val1
export p_p2=val2
$ cat go.bash
. ./config.data
echo "select * from dbtable where p1 = '$p_p1' and p2 like '$p_p2%' order by p1"
$ bash go.bash
select * from dbtable where p1 = 'val1' and p2 like 'val2%' order by p1
然后输出go的输出。bash到MySQL,瞧,希望你不会破坏你的数据库:-)。
我在想同样的事情时发现了这条线索。这启发了我(注意反节拍)
$ echo $MYTEST
pass!
$ cat FILE
hello $MYTEST world
$ eval echo `cat FILE`
hello pass! world