使用grep和map查找扩展名为.png的文件名,但输出时不使用扩展名



使用grepmap,我的Perl脚本将文件名(工厂名(返回为";Genus_species.png";。但是,我更愿意输出这些没有.png扩展名的文件名。也就是说,我仍然希望我的grep/map表达式只查找扩展名为.png的文件名。我该怎么做?请告知。谢谢

这是我的脚本:

#!/usr/bin/perl
use strict;
use warnings;
my $dir = '/Users/jdm/Desktop/xampp/htdocs/cnc/images/plants';
opendir my $dfh, $dir  or die "Can't open $dir: $!";
my @files = 
map { s/1.pngz/.png/r } # Removes "1" from "Genus_species1.png" file names/ also finds "Genus_species.png" file names
grep { /^[^2-9]*.pngz/i && /_/ } # Excludes file names with numbers 2-9 such as "Genus_species2-9.png"
readdir $dfh; # Returns one file name per plant as "Genus_species.png" 
foreach my$file (@files) {
print "$filen";
}

这是输出:

Ilex_verticillata.png
Asarum_canadense.png
Ageratina_altissima.png
Lonicera_maackii.png
Chelone_obliqua.png
Acalypha_deamii.png

以下是不带.png扩展名的首选输出:

Ilex_verticillata
Asarum_canadense
Ageratina_altissima
Lonicera_maackii
Chelone_obliqua
Acalypha_deamii

同样,我仍然希望只找到扩展名为.png的文件名,但输出时不使用.png扩展名。

放入最后一个循环:

$file =~s/.png//;

打印前。

您可以通过替换来删除扩展:

foreach my $file (@files) {
print $file =~ s/.png$//r, "n";
}

或者,您可以使用substr:

foreach my $file (@files) {
print substr($file, 0, -4), "n";
}

或者,您可以使用匹配:

foreach my $file (@files) {
print $file =~ /(.*).png$/, "n";
}

glob的使用简化了问题

use strict;
use warnings;
use feature 'say';
my $dir = '/Users/jdm/Desktop/xampp/htdocs/cnc/images/plants';
my @files = map { s/1|(2-9)|(.png)//g; $_ } glob("$dir/*.png");
say for @files;

所以您想要更改xxx1.pngxxxxxx.pngxxx

要做到这一点,只需更换

s/1.pngz/.png/r

带有

s/1?.pngz//r

最新更新