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