Created
June 11, 2026 08:40
-
-
Save calvinclaus/57d91538f39a2e80126697d80aa79f52 to your computer and use it in GitHub Desktop.
orderlogs.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| require 'time' | |
| if ARGV.length != 1 | |
| puts "Usage: ruby orderlogs.rb input.log" | |
| exit 1 | |
| end | |
| input_file = ARGV[0] | |
| output_file = "output.log" | |
| begin | |
| lines = File.readlines(input_file) | |
| entries = [] | |
| current_entry = [] | |
| timestamp_regex = /^\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z\]/ | |
| lines.each do |line| | |
| if line.match?(timestamp_regex) | |
| entries << current_entry.join if current_entry.any? | |
| current_entry = [line] | |
| else | |
| current_entry << line | |
| end | |
| end | |
| entries << current_entry.join if current_entry.any? | |
| # Sort entries by the timestamp in the first line | |
| sorted_entries = entries.sort_by do |entry| | |
| match = entry.match(timestamp_regex) | |
| if match | |
| Time.parse(match[0][1..-2]) rescue Time.at(0) | |
| else | |
| Time.at(0) | |
| end | |
| end | |
| File.open(output_file, "w") do |f| | |
| sorted_entries.each { |entry| f.puts(entry.chomp) } | |
| end | |
| puts "Sorted log written to #{output_file}" | |
| rescue => e | |
| puts "Error: #{e.message}" | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment