我想用一个文件中的属性替换另一个文件中的属性。 (我是 ruby 的新手,了解过 Ruby 和 YAML。我有 Java 背景)
例如。
文件 1
server_ip_address=$[ip]
value_threshold=$[threshold]
system_name=$[sys_name]
文件 2
ip=192.168.1.1
threshold=10
sys_name=foo
ruby 脚本应将 $ 值替换为其实际值(我不知道 $[] 是否是 ruby 中使用的格式。文件 1 和 2 是否必须是 YAML 文件或 erb 文件?)并生成文件 1 为:
server_ip_address=192.168.1.1
value_threshold=10
system_name=foo
我在网上搜索了这个,但无法用正确的关键字来表达它,无法在谷歌上找到解决方案/指向解决方案/引用资料的指针。这如何通过 ruby 脚本完成?
谢谢
最佳答案
如果你可以切换格式,这应该很简单:
require 'yaml'
variables = YAML.load(File.open('file2.yaml'))
template = File.read('file1.conf')
puts template.gsub(/\$\[(\w+)\]/) { variables[$1] }
您的模板可以保持原样,但替换文件如下所示:
ip: 192.168.1.1
threshold: 10
sys_name: foo
这使得使用 YAML 库更容易阅读。
关于ruby - 在 Ruby 中将一个文件中的属性替换为另一个文件中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14974663/