Output in the Correct Order
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.