use strict; use warnings; my %cols; my $ctr=0; my @data = map {/(.*),(.*), (.*)/; $2."\t"x($cols{"\t$3"}//=++$ctr)."$1\n" } ; print sort {$cols{$a}<=>$cols{$b}} keys %cols; print "\n", @data; __DATA__ 52,1427766557, bob 12,1427766556, bob 5,1427766555, bill 10,1427766554, joe 23,1427766553, bob