"Mark Probert" <probertm@nospam-acm.org> schrieb im Newsbeitrag
news:Xns9549BE97C59B0probertmnospamacmorg@198.161.157.145...
Hi.
I have a need to update a config file. It uses '#' as a line comment
marker. The config file looks like:
# file comment
#
name1:foo1:bar:other
name2:foo2:bar:other
name3:foo3:bar:other
name4:foo4:bar:other
The name:foo combination is unique.
What is the most efficient way to read in the file, update the line, and
then write it back to the file. One update would be to place a '#' in col
1
#name3:foo3:bar:other
Any thoughts appreciated.
-mark.
Some code thoughts below
Regards
robert
# match keys
COMMENT = lambda {|key, val| "# #{key}:#{val}"}
DELETE = lambda { nil }
tasks = {
"foo:bar" => COMMENT,
"foo1:bar1" => DELETE,
}
conf = File.readlines("conf.txt")
# manipulate
conf.map! do |line|
if /^([^:]+:[^:]+):(.*)$/ =~ line && (fun = tasks[$1])
fun.call $1, $2
else
line
end
end
# remove deleted lines
conf.compact!
File.open("conf-1.txt", "w") {|io| io.puts conf }
···
#
# alternative -----------------------------------------
#
# use regexp as line matcher
tasks = {
/^foo1:bar1:/ => lambda {|line| "# #{line}"},
/^\s*#\s*foo.bar:/ => lambda {|line| line.sub(/^\s*#\s*/, '' )},
}
conf = File.readlines("conf-1.txt")
# manipulate
conf.map! do |line|
p,f = tasks.find {|patt, fun| patt =~ line}
f ? f.call( line ) : line
end
# remove deleted lines
conf.compact!
File.open("conf-2.txt", "w") {|io| io.puts conf }