Very noob question
I have this file
users_properties.cfg
[user1]
command1 = cmdA
command2 = cmdB
command3 = cmdC
[user2]
command1 = NA
To do something like: foreach [section] => param = value
Before someone recommend me : rubygem inifile, puppetmaster + clients , none of them have internet access, + I’ve been prohibited to install any 3rd party applications/module from internet w/o special permission, so, I just have to reinvent the wheel…
Hi @fritz001,
actually it’s not that noob of a question
What you’re looking for is a regular expression.
A regular expression lets you define a pattern of text that you want to match.
This INI file follows a specific pattern.
Using a regular expression you can match the pattern & extract the data into Ruby objects so you can work with the data. We call this “parsing”.
Ok, I’ve got my inspiration from **[parseconfig] gem
require 'fileutils'
@data = {}
section = nil
cmds = []
File.readlines('/root/users_prop.ini').each do |line|
line = line.chomp
unless (/^\#/.match(line))
if (line =~ /^\[(.*)\]\s*$/)
section = $1
@data[section] = {}
next
end
if (line =~ /^([^=]+?)\s*=\s*(.*?)\s*$/)
param, val = line.split(/\s*=\s*/, 2)
if !section
next
end
var_name = "#{param}".chomp.strip
val = val.chomp.strip
@data[section][var_name] = val
end
end
end
@data.each do |k,hash|
puts "~~~ #{k} ~~~"
hash.each do |a,b|
puts a+" ===> "+ b
end
end
P.S. It dosn’t look for me like regex search !!
This:
/^\[(.*)\]\s*$/
And this:
/^([^=]+?)\s*=\s*(.*?)\s*$/
And this:
/\s*=\s*/
Are ALL regular expressions