bees
bees

Reputation: 143

Parse custom logfile to an array of hashes

I want to parse a logfile which has 3 entries. It looks like this:

Start: foo
Parameters: foo
End: foo

Start: other foo
Parameters: other foo
End: other foo

....

The foo is what I want. It would be nice if the result looks like this:

logs = [
{
  :start=>"foo",
  :parameters=>"foo",
  :end=>"foo"
},
{
  :start=>"other foo",
  :parameters=>"other foo",
  :end=>"other foo"
}
]

I know some regex, but it's hard for me to understand how I to this over multiple lines. Thanks!

Upvotes: 2

Views: 419

Answers (3)

Jonas Elfström
Jonas Elfström

Reputation: 31428

It could be a problem to read the whole logfile into memory like Wayne does.

log = []
h = {}
FasterCSV.foreach("log.log", :col_sep => ":") do |row|
  name, value = *row
  if !name.nil?
    h[name.downcase.to_sym]=value
    if name=="End"
      log<<h
      h={}
    end
  end
end

log
=> [{:end=>" foo", :start=>" foo", :parameters=>" foo"},
    {:end=>" other foo", :start=>" other foo", :parameters=>" other foo"}]

Upvotes: 3

Wayne Conrad
Wayne Conrad

Reputation: 108039

#!/usr/bin/ruby1.8

require 'pp'

logfile = <<EOS
Start: foo
Parameters: foo
End: foo

Start: other foo
Parameters: other foo
End: other foo
EOS

logs = logfile.split(/\n\n/).map do |section|
  Hash[section.lines.map do |line|
    key, value = line.chomp.split(/: /)
    [key.downcase.to_sym, value]
  end]
end

pp logs
# => [{:end=>"foo", :parameters=>"foo", :start=>"foo"},
# =>  {:end=>"other foo", :parameters=>"other foo", :start=>"other foo"}]

Upvotes: 4

cam
cam

Reputation: 14222

The best way to do this is with a multiline regex:

logs = file.scan /^Start: (.*)\nParameters: (.*)$\nEnd: (.*)$/
#  => [["foo", "foo", "foo"], ["other foo", "other foo", "other foo"]]
logs.map! { |s,p,e|  { :start => s, :parameters => p, :end => e } }
#  => [ {:start => "foo", :parameters => "foo", :end => "foo" }, ... ]

Upvotes: 5

Related Questions