Ruby Filter Script

It’s pretty easy to use a ruby script as part of a Linux or Unix pipe process to filter output of another script or set of commands. You can just use something like the following:

#!/usr/bin/env ruby

while line = STDIN.gets
  puts "filtered: #{line}"
end

The STDIN.gets is the magic. It just takes whatever the output of the preceding scripts and pipes it in. Then you can make the script executable and run it. If this script is named filter.rb, then you could run something like:

$> cat log.txt | ./filter.rb

If your log.txt file looks like:

line 1
line 2
line three

Then the results of this program will be:

filtered: line 1
filtered: line 2
filtered: line three

I wrote this up because I regularly search around for this but it was hard to find exactly what I’m looking for, so hopefully it will be easier the next time I search. :)

Categories: development

« Something is installing Rake 0.9.0 when I `bundle install` The State of Ruby and Testing »

Comments