Using map and grep to find file names with underscores

Viewed 127

My Perl script searches a directory for file names using the map and grep expressions. The script works, but I want to also specify in the map and grep expressions that ALL outputted file names must also include underscores in their names. Sounds simple enough, but I can't figure out how to do this. Please advise. Thanks.

Here's my original script that fails to limit outputted file names to only those with underscores in their names:

#!/usr/bin/perl
use strict;
use warnings;

my $dir = '/Users/jdm/Desktop/xampp/htdocs/cnc/images/plants';
opendir(my $DIR, $dir);
my @files =
   map s/1//rg,
      grep /^[^2-9]*\.png\z/i,
        readdir($DIR);

foreach my$file (@files) {
   print "$file\n";
}

Here's the output. Notice how file names without underscores such as "Asarumcanadense.png" are unwantingly outputted:

Ilex_verticillata.png
Asarum_canadense.png
Ageratina_altissima.png
Lonicera_maackii.png
Chelone_obliqua.png
Asarumcanadense.png

Modifying the map/grep expression as below to include only file names with underscores in the middle of their names created a syntax error:

my @files =
 map s/*_*1//rg,
    grep /^_*[^2-9]*\.png\z/i,
      readdir($DIR); # outputted files must also include an underscore

Again, please advise how to specify in the map and grep expressions that ALL outputted file names must also include underscores in their names. Thanks.

1 Answers

Add the needed condition to grep:

my @files =
   map { s/1//rg }
      grep { /^[^2-9]*\.png\z/i && /_/ } 
        readdir($DIR);
Related