Skip to content

Instantly share code, notes, and snippets.

@rab
Created July 2, 2010 19:23
Show Gist options
  • Save rab/461784 to your computer and use it in GitHub Desktop.
Save rab/461784 to your computer and use it in GitHub Desktop.
first_name last_name employer
Fred Flintstone Bedrock Quarry
Clark Kent The Daily Planet
Ralph Kramden Metro Bus
Joe Friday LAPD
David Hansson 37Signals
Jim Weirich EdgeCase
#!/usr/bin/env ruby
require 'rubygems'
require 'fastercsv'
input_files = [ ]
File.open('first.csv', 'w') do |f|
f.write <<-CSV
first_name,last_name,employer
Fred,Flintstone,Bedrock Quarry
Clark,Kent,The Daily Planet
CSV
end
input_files << 'first.csv'
File.open('second.csv', 'w') do |f|
f.write <<-CSV
first_name,last_name,employer
Ralph,Kramden,Metro Bus
Joe,Friday,LAPD
CSV
end
input_files << 'second.csv'
File.open('third.csv', 'w') do |f|
f.write <<-CSV
first_name,last_name,employer
David,Hansson,37Signals
Jim,Weirich,EdgeCase
CSV
end
input_files << 'third.csv'
output_file = 'combined.csv'
headers = nil
all_rows = []
input_files.each do |input_file|
csv = FasterCSV.table(input_file, :headers => true)
in_headers, *in_rows = csv.to_a
headers ||= in_headers
all_rows.concat(in_rows)
end
FasterCSV.open(output_file, 'w') do |csv|
csv << headers
all_rows.each {|row| csv << row }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment