!/usr/bin/perl use strict; use warnings; my $file_in='test.txt'; my $file_out='test.out.txt'; my @data; { open(my $fh, '<', $file_in) or die("ERROR open $file_in ($!)\n"); while(my $line=<$fh>) { push(@data,$line); if(my ($name)=$line=~/(\w+)\.xml\.gz/) { push(@{$order{$name}},$#data); } } close($fh); } for my $arr (values(%order)) { while(@$arr>2) { my $pos=shift(@$arr); splice(@data,$pos,1); } } { open(my $fh, '>', $file_out) or die("ERROR open $file_out ($!)\n"); print $fh @data; close($fh); }