将一个文件中的属性替换为Ruby中另一个文件中的属性 [英] Replace properties in one file from those in another in Ruby
问题描述
我要替换一个文件中的属性。 (我是ruby的新手,并且了解Ruby和YAML。我有Java背景)
例如。
文件1
server_ip_address = $ [ip]
value_threshold = $ [threshold ]
system_name = $ [sys_name]
文件2
ip = 192.168.1.1
阈值= 10
sys_name = foo
ruby脚本应将$值替换为其实际值(我不知道$ []是否为ruby中使用的格式。也文件1和2必须是YAML文件还是erb文件?)并生成文件1如下:
server_ip_address = 192.168。 1.1
value_threshold = 10
system_name = foo
我在网上搜索了此内容,但无法用正确的关键字来表达它,以在Google上找到解决方案/参考材料的解决方案/指针。怎么用ruby脚本完成?
谢谢
如果您可以切换格式,则应该很简单:
需要'yaml'
变量= YAML.load(File.open('file2.yaml'))
模板= File.read('file1.conf')
将template.gsub(/ \ $ \ [(\w +)\] /){变量[$ 1]}
您的模板可以保持原样,但替换文件如下所示:
ip:192.168.1.1
阈值: 10
sys_name:foo
这使使用YAML库很容易阅读。 / p>
I want to replace properties in one file from those in another. (I am new to ruby, and read about Ruby and YAML. I have a Java background)
Eg.
File 1
server_ip_address=$[ip]
value_threshold=$[threshold]
system_name=$[sys_name]
File 2
ip=192.168.1.1
threshold=10
sys_name=foo
The ruby script should replace the $ values by their real values (I do not know if $[] is the format used in ruby. Also do Files 1 and 2 have to be YAML files, or erb files?) and produce File 1 as :
server_ip_address=192.168.1.1
value_threshold=10
system_name=foo
I searched the web for this, but could not express it in the right keywords to find a solution/pointer to a solution/reference material on google. How can this be done by a ruby script?
Thanks
If you can switch the formats, this should be as easy as:
require 'yaml'
variables = YAML.load(File.open('file2.yaml'))
template = File.read('file1.conf')
puts template.gsub(/\$\[(\w+)\]/) { variables[$1] }
Your template can stay as-is, but the substitution file would look like:
ip: 192.168.1.1
threshold: 10
sys_name: foo
This makes it easy to read in using the YAML library.
这篇关于将一个文件中的属性替换为Ruby中另一个文件中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!