use strict; use warnings; # @ID to keep unique id's (in order they are seen) # %T to group things by id. Make it HoA (Hash of Arrays) my (@ID, %T); ... while () { my ($date, $id, $kw) = /\[(.+?)\]/g; my $txt; next unless $kw; $txt = "$+ to P5" if $kw =~ /^(Input Message)/; $txt = $+ if $kw =~ /^(Orchestration Started)$/; $txt = $+ if $kw =~ /^ProcessName:(.*)/; # note the opportunity to merge some regexes above next unless $txt; push @ID, $id unless $T{$id}; push @{ $T{$id} }, "$date,$id,$txt \n"; } for my $group (@T{ @ID }) { # this is a hash slice! print OUT for @$group; }