Replace properties in one file from those in anoth

2019-07-22 03:43发布

问题:

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.



标签: ruby yaml erb