use strict; use warnings; my %reformat; my $re = qr{^(H\d+,\d+,)(.*)$}; open (NEW, ">", "Notes_Test_OUTPUT.txt" ) or die "could not open:$!"; open (FILE, "<", "Notes_Test.txt") or die "could not open:$!"; while () { chomp; /$re/; push @{ $reformat{$1} }, $2; print NEW $_, join ' ', @{ $reformat{$_} } for keys %reformat; } close (FILE); close (NEW);