Using Ruby to skim log files

Say we have a bunch of log files, whose last line is the main thing you care about(you might imagine it has a distinct prefix like “ANSWER”–I know, that’s contrived :p The following code assumes the script is in the same directory as the log files. It gets all the files ending in .txt, opens them, puts the name of the file to the console, and then puts the result line on the console. We could keep appending to a file, but for a “throwaway” script, we can just make do with: ./process.rb > results.txt(OS X, assuming chmod +x process.rb was applied), or ruby results.txt > process.rb (on Windows).

#!/usr/bin/env ruby

file_list = Array.new
file_list = Dir[“*.txt“]
file_list.each do |file|
File.open(file,”r“) do|f_object|
print(file.to_s + “ “)
f_object.each_line {|line| puts line if line =~ /ANSWER/ }
end
end

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s