From: Florian Gross Date: 2004-03-06T13:54:42+09:00 Subject: Re: Ruby translation for UNIX scripting command Mark Hubbart wrote: > If, on the other hand, you want a script that you can call like this: > > % myscript input_file output_file > > then you will be needing to read up a little more in ruby, I think. But > here's some code for an example: > > filtered_data = File.open("input_file") do |file| > file.read.grep(/pattern/).map{|line| line.split[3]}.join "\n" > end > > File.open("output_file") do |file| > file.write filtered_data > end This can be simplified to: filtered_data = File.read("input_file").grep(/pattern/) \ .map { |line| line.split[3] } File.open("output_file") do |file| file.puts filtered_data end It might however be better to do all this in one pass over the data without using any buffers -- I'd do that like this: filtered_data = Array.new File.foreach("input_file") do |line| if md = /^(#\w+) ([\d:]+) (<\w+>) (.*?)$/.match(line) channel, time, nick, text = md.captures filtered_data << text end end File.open("output_file") do |file| file.puts filtered_data end This implementation does also allow one to keep a part of the matching line not surrounded by whitespace. (Which means that one could also use it on CSV data or similar input.)