my %hash; while(){ chomp; my @line = split /\t/; my $first = shift @line; $hash{$first}{$_}++ for @line; } foreach( sort keys %hash ){ print STDOUT "$_\t".join("\t", sort keys %{$hash{$_}})."\n"; } __DATA__ text1 text-a text-a text-b text-a text1 text-c text2 text-a text-b text2 text-b text-d