# use an all-perl approach: opendir( DIR, "." ); @files = sort {$b cmp $a} grep /BC.*?\.txt$/, readdir DIR; close DIR; open( OUT, ">BCfile.name" ); for ( grep !/Liver/, @files ) { s/\..*/\n/; print OUT; } close OUT; # OR... a little bit of reliance on a sub-shell is okay too; # the next four lines do the same thing just as well: @files = map {s/\..*//; $_} grep !/Liver/, `ls -r *BC*.txt`; open OUT, ">BCfile.name"; print OUT join "", @files; close OUT;