Skip to content

Instantly share code, notes, and snippets.

@hank
Created October 1, 2009 01:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hank/198622 to your computer and use it in GitHub Desktop.
Save hank/198622 to your computer and use it in GitHub Desktop.
A totally awesome Ruby script for concatenating files together in columns
#!/usr/bin/ruby
# Original credits to Geet Duggal
# Concatenates an arbitrary number of files together into columns
# Columns map to lines in each file.
# Requirement: Files be of the same length.
# Oh, and cheers!
require "pp"
filez = ARGV.map do |fname|
begin
File.open(fname)
rescue
puts $!
exit
end
end
# Make sure all files have the same number of lines
num_lines = 0
num_lines = filez.map{ |f| f.readlines.length }.uniq
filez.each{|f| f.rewind }
if num_lines.length == 1
num_lines = num_lines[0]
else
puts "All files need to have the same number of lines"
Process.exit(1)
end
# Go ahead and actually perform concatenation
while num_lines > 0
puts filez.map{ |file| file.readline.chomp.split("\t") }.flatten.join("\t")
num_lines -= 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment