Skip to content

Instantly share code, notes, and snippets.

@sonota88
Last active December 14, 2015 03:29
Show Gist options
  • Save sonota88/5021285 to your computer and use it in GitHub Desktop.
Save sonota88/5021285 to your computer and use it in GitHub Desktop.
ログを時間でフィルタするやつ
# -*- coding: utf-8 -*-
def format_datetime(y, m, d, hour, min)
"%04d-%02d-%02d %02d:%02d" % [y, m, d, hour, min]
end
def auto_hour(from_or_to)
if from_or_to == :from
0
elsif from_or_to == :to
23
else
raise "must not happen"
end
end
def auto_min(from_or_to)
if from_or_to == :from
0
elsif from_or_to == :to
59
else
raise "must not happen"
end
end
def normalize_datetime(str, from_or_to)
ymd_sep = /[-\/]/
if /^(\d{4})#{ymd_sep}?(\d{2})#{ymd_sep}?(\d{2})[^-\/](\d{2}):?(\d{2})$/ =~ str
# yyyy-mm-dd hh:mm
format_datetime($1, $2, $3, $4, $5)
elsif /^(\d{2})#{ymd_sep}?(\d{2})[^-\/](\d{2}):?(\d{2})$/ =~ str
# mm-dd hh:mm
format_datetime(Time.now.year, $1, $2, $3, $4)
elsif /^(\d{4})#{ymd_sep}?(\d{2})#{ymd_sep}?(\d{2})$/ =~ str
# yyyy-mm-dd
format_datetime($1, $2, $3, auto_hour(from_or_to), auto_min(from_or_to))
elsif /^(\d{2})#{ymd_sep}(\d{2})$/ =~ str
# mm-dd
format_datetime(Time.now.year, $1, $2, auto_hour(from_or_to), auto_min(from_or_to))
elsif /^(\d{2}):(\d{2})$/ =~ str
# hh:mm
format_datetime(Time.now.year, Time.now.month, Time.now.day, $1, $2)
elsif /^(\d{2})(\d{2})$/ =~ str
# hhmm
format_datetime(Time.now.year, Time.now.month, Time.now.day, $1, $2)
else
raise "invalid datetime argument"
end
end
file = ARGV[0]
t0 = normalize_datetime(ARGV[1], :from)
t1 = normalize_datetime(ARGV[2], :to)
in_span = false
in_span_old = false
lineno_from = nil
lineno_to = nil
lineno = 1
open(file){|fin|
while line = fin.gets
if /^(\d{4}-\d{2}-\d{2} \d{2}:\d{2})/ =~ line
datetime = $1
_in_span = t0 <= datetime && datetime <= t1
if in_span_old == false && _in_span
in_span = true
lineno_from = lineno
elsif in_span_old == true && ! _in_span
in_span = false
lineno_to = lineno - 1
break
else
;
end
end
if in_span
# print "#{lineno}: "
puts line
end
in_span_old = in_span
lineno += 1
end
}
puts "----"
puts "executed at: #{Time.now}"
puts "arguments: #{ARGV}"
puts "span: #{t0} - #{t1}"
puts "lineno from: #{lineno_from}"
puts "lineno to: #{lineno_to}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment