Skip to content

Instantly share code, notes, and snippets.

@iwazer
Created August 25, 2011 01:30
Show Gist options
  • Save iwazer/1169757 to your computer and use it in GitHub Desktop.
Save iwazer/1169757 to your computer and use it in GitHub Desktop.
分割されたApacheのログをマージする。This program merge divided Apache log.
#!/usr/bin/env ruby
files = ARGV.map {|f| File.open(f)}
DT_PARSE = /[^\[]+\[([0-9]+)\/([A-z0-9]+)\/([0-9]+):([0-9]+):([0-9]+):([0-9]+) ([0-9+-]+)\].+/
MONTH = {
'Jan'=>0,'Feb'=>1,'Mar'=>2,'Apr'=>3,'May'=>4,'Jun'=>5,
'Jul'=>6,'Aug'=>7,'Sep'=>8,'Oct'=>9,'Nov'=>10,'Dec'=>11}
class PreRead
attr_accessor :file, :line, :dt
def initialize file, line, dt
@file = file
@line = line
@dt = dt
end
end
pre_reads = files.map {|f| PreRead.new(f, nil, 0)}
def parse_dt str
if DT_PARSE =~ str
year = $1.to_i - 2000
month = MONTH[$2]
day = $3.to_i-1
hour = $4.to_i
min = $5.to_i
sec = $6.to_i
(year*365 + month*31 + day)*86400 + hour*3600 + min*60 + sec
else
nil
end
end
begin
a = pre_reads.reject {|v| not v.line.nil?}
a.each do |pr|
dt = nil
begin
break if pr.file.eof?
pr.line = pr.file.readline
dt = parse_dt(pr.line)
end while dt.nil?
pr.dt = dt
end
pr = pre_reads.min {|a,b| a.dt<=>b.dt}
puts pr.line
pr.line = nil
if pr.file.eof?
pre_reads.delete(pr)
pr.file.close
end
end while pre_reads.length > 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment