Replace properties in one file from those in another in Ruby

ⅰ亾dé卋堺 提交于 2019-12-11 00:37:39

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/14974663/replace-properties-in-one-file-from-those-in-another-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!