在属性文件中替换环境变量 [英] Replacing environment variables in a properties file

查看:90
本文介绍了在属性文件中替换环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linux中,说我有以下文件(例如conf.properties):

In Linux, say I have the following file (e.g. conf.properties):

HOST_URL=http://$HOSTNAME
STD_CONFIG=http://$HOSTNAME/config
USER_CONFIG=http://$HOSTNAME/config/$unconfigured

我想创建一个替换了所有环境变量的文件...假设环境变量$ HOSTNAME为'myhost'并且未设置$ unconfigured,脚本应产生以下输出:

I want to create another file with all the environment variables replaced...e.g. say the environment variable $HOSTNAME is 'myhost' and $unconfigured is not set, a script should produce the following output:

HOST_URL=http://myhost
STD_CONFIG=http://myhost/config
USER_CONFIG=http://myhost/config/

我本以为可以用一种简单的单线形式,使用某种sed/awk魔术来完成此操作,但是我不是专家,我的搜索也很普遍,因此,感谢您的帮助.

I was thinking this could be done in a simple one-liner with some sort of sed/awk magic, but I'm no expert and my searches have been in vein, so appreciate any help.

我应该提到该文件实际上可以是任何格式的文本文件,例如xml.我只想用环境中当前设置的值替换任何看起来像env变量的值.

I should mention that the file can really be any format text file, for example xml. I just want to replace anything that looks like an env variable with whatever is currently set in the environment.

推荐答案

sed 's/$HOSTNAME/myhost/g;s/$unconfigured//g' yourfile.txt > another_file.txt

更新:

根据您问题中的更新,这将不是一个好的解决方案.

update:

Based on updates in your question, this won't be a good solution.

这基于

This is based on an answer to a related question. I've hacked at it (I'm unfamiliar with perl) to remove undefined vars.

perl -p -e 's/\$\{([^}]+)\}/defined $ENV{$1} ? $ENV{$1} : $&/eg; s/\$\{([^}]+)\}//eg' yourfile.txt

应适用于任何输入文本文件,但是您将需要使用${...}格式定义vars,该格式可简化字符串匹配.

Should work for any input text file, however you will need to define vars using the ${...} format which simplifies the string matching.

(关于eval邪恶的言论转移到

(rant regarding the evilness of eval moved to a separate post so as not to confuse readers)

这篇关于在属性文件中替换环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆