Output in the Correct Order Ok lets say we get a input the following csv file (all entries are quoted strings)

ID,    Before,   After,   Value 
 1,         3,       5,    Cat
 2,         5,        ,    Apple
 3,         4,       1,    Dog
 4,          ,       3,    Elephant
 5,         1,       2,    Banana


Output a csv file in which the entries are usage sequence order.

ID,    Before,   After,   Value
 2,         5,        ,    Apple 
 5,         1,       2,    Banana
 1,         3,       5,    Cat
 3,         4,       1,    Dog
 4,          ,       3,    Elephant


Notes: 
The Values may not necessarily appear in alphabetical order all the time, just that in this example they are. 
No revaluing of the IDs being use. They must be the same as input.

Input and Output files will be pass as args to program.
Ruby 109 108

Saved one whole character by using randomization instead of searching!

h,*t=[*$&lt;]
t.shuffle!until t.each_cons(2).all?{|c|a,b=c.map{|y|y.lstrip.split /[,\s]+/}
a[1]==b[0]}
puts h,t


This only prints to stdout, so to save to a file use ruby csv.rb in.csv &gt; out.csv.

$ cat test.csv 
ID,    Before,   After,   Value 
 1,         3,       5,    Cat
 2,         5,        ,    Apple
 3,         4,       1,    Dog
 4,          ,       3,    Elephant
 5,         1,       2,    Banana
$ ruby csv.rb test.csv 
ID,    Before,   After,   Value 
 2,         5,        ,    Apple
 5,         1,       2,    Banana
 1,         3,       5,    Cat
 3,         4,       1,    Dog
 4,          ,       3,    Elephant


Old version

puts gets,[*$&lt;].permutation.find{|x|x.each_cons(2).all?{|c|a,b=c.map{|y|y.lstrip.split /[,\s]+/}
a[1]==b[0]}}


It simply finds the permutation of the lines where, for each line, the second column (Before) equals the first column (ID) of the next line.