开发者

Parse custom logfile to an array of hashes

开发者 https://www.devze.com 2023-02-03 16:23 出处:网络
I want to parse a logfile which has 3 entries. It looks like this: Start: foo Parameters: foo End: foo Start: other foo

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

..开发者_Python百科..

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!


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" }, ... ]


#!/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"}]


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"}]
0

精彩评论

暂无评论...
验证码 换一张
取 消