Skip to content

Instantly share code, notes, and snippets.

@granolocks
Created December 23, 2014 19:33
Show Gist options
  • Select an option

  • Save granolocks/c792fe7f18be39aaa234 to your computer and use it in GitHub Desktop.

Select an option

Save granolocks/c792fe7f18be39aaa234 to your computer and use it in GitHub Desktop.
attr_stat
#!/usr/bin/env ruby
require 'csv'
@file = ARGV[0]
@attr = ARGV[1]
if ARGV[2]
@pattern = eval(ARGV[2]) # >:)
end
if @file && @attr
data = []
CSV.foreach(@file, headers: true) do |row|
data << Hash[row.headers.zip(row.fields)]
end
summaries = {}
data.each do |hsh|
hsh.each do |k,v|
summaries[k] ||=[]
summaries[k] << v
end
end
set = summaries[@attr]
if @pattern
set = set.select!{|x| x =~ @pattern}
end
counters = Hash.new(0)
set.each do |match|
counters[match] += 1
end
counters.to_a
.sort_by {|_,count| count}
.reverse
.each do |val, count|
puts "%-5d: %s" % [count, val]
end
else
puts "usage: #{__FILE__} something.csv attr /somepattern/i"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment