Skip to content

Instantly share code, notes, and snippets.

@spiegela
Created August 10, 2012 04:07
Show Gist options
  • Save spiegela/3310981 to your computer and use it in GitHub Desktop.
Save spiegela/3310981 to your computer and use it in GitHub Desktop.
Command line script to Parse CSV files
#!/usr/bin/env ruby
# How about an awesome command-line script
# that replaces your usage of "awk -F, ..."
# for like 99% of cases.
#
# Also, importantly, it supports CSV features
# like escaping commas when quoted
#
# Usage: csv.rb [options] <filename>
# -c <column 1> <column 2> ..., Specify the columns to print
# --column
# -d, --delimeter <delimeter> Specify the delimeter when printing the columns back out (default: " ")
#
require 'rubygems'
require 'csv'
require 'optparse'
options = {}
options[:delimeter] = " "
options[:columns] = []
optparse = OptionParser.new do |opts|
opts.banner = "Usage: csv.rb [options] <filename>"
opts.on( "-c",
"--column <column 1> <column 2> ...",
"Specify the columns to print"
) do |column_list|
cols = []
column_list.scan(/(\D)?(\d+)/).each do |d, n|
case d
when nil, ","
cols << n.to_i
when "-"
cols.push *((cols.last + 1)..n.to_i).to_a
end
end
options[:columns] = cols
end
opts.on( "-d",
"--delimeter <delimeter>",
"Specify the delimeter when printing the columns back out (default: \" \")"
) do |delimeter|
options[:delimeter] = delimeter
end
end
optparse.parse!
selection = options[:columns].empty? ? ->(r){ r } : ->(r){ r.values_at(*options[:columns]) }
read_csv = ARGV.empty? ? ->(&block){ CSV($stdin){ |c| c.each{|r| block.call(r) } } } : ->(&block){ CSV.foreach(ARGV[0]){|r| block.call(r) } }
read_csv.call do |r|
begin
puts selection.call(r).join(options[:delimeter])
rescue Errno::EPIPE
break
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment