open(IN, '<', "test.in"); open(OUT, '>', "test.out"); while () { chomp; next unless /\S/; my ($name, $num) = /(.*)\s+(B-.*)/; $data{$name}{$num} = 1; } foreach my $name (sort keys %data) { print OUT "$name "; print OUT join ', ', sort { $a cmp $b } keys %{$data{$name}}; print OUT "\n\n"; } output: Tsuneyuki, Shinji B-6-IN11 Xu, Guo Qin B-5-OR10, B-5-OR9, B-6-IN12 Zhang, Yong Ping B-5-OR10