my %hash; for (@filenames) { chomp; push @{$hash{$3}}, $_ if ($_ =~ /(.+)\/(.+)\/(.+)\/.+/); } for (keys %hash) { print "#".uc($_)."\n" ; print $_."\n" for (@{$hash{$_}}); print "#END ".uc($_)."\n" ; }