Wednesday, August 24, 2011

Grokking CSVs Easier in STDOUT

#!/usr/bin/env ruby
require 'rainbow' # To make things a bit more readable
require 'csv' # using just split won't work cause of \n in some fields

if ARGV[0].nil?
 puts "#{$0} <csv_file>"
 exit
end
i = 0
headers = []
header_index = 0
CSV.foreach(ARGV[0], :quote_char => '"', :col_sep =>',', :row_sep =>:auto) do |line|
 line.each do |column|
   if i == 0
     headers.push(column)
   end
   if i % 2 == 0
     puts headers[header_index].upcase
     puts "#{column}\n"
   else
     puts headers[header_index].upcase.inverse
     puts "#{column}\n".inverse
   end
   header_index += 1
 end
 header_index = 0
 i += 1
end

No comments:

Post a Comment