Skip to content

Instantly share code, notes, and snippets.

@nathankleyn
Last active April 19, 2018 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathankleyn/1e69134be4f179c761e742ff8dfbb3de to your computer and use it in GitHub Desktop.
Save nathankleyn/1e69134be4f179c761e742ff8dfbb3de to your computer and use it in GitHub Desktop.
Relative times within log files
#!/usr/bin/env ruby
# Takes a log where lines have [HH:MM:SS] in front of the lines, and turns them
# into +HH:MM:SS since start of the script (ie. relative times).
#
# Any line that has no time at the start will be printed as is.
#
# Usage: relative_time_logs < some.log
time_regex = /^\[(?<hours>\d\d):(?<minutes>\d\d):(?<seconds>\d\d)\]/
STDIN.each_line.reduce(nil) do |start_time, line|
match = line.match(time_regex)
# If the line doesn't start with a time, just leave it alone.
unless match
puts line
next start_time
end
hours = match[:hours].to_i
minutes = match[:minutes].to_i
seconds = match[:seconds].to_i
line_time = (hours * 60 * 60) + (minutes * 60) + seconds
start_time = line_time if start_time.nil?
seconds_diff = line_time - start_time
puts line.sub(time_regex, "[+#{Time.at(seconds_diff).utc.strftime('%H:%M:%S')}]")
start_time
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment