Created
October 1, 2009 01:07
-
-
Save hank/198622 to your computer and use it in GitHub Desktop.
A totally awesome Ruby script for concatenating files together in columns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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