Perl 使用grep和map查找扩展名为.png的文件名,但不输出扩展名
使用grep和map,我的Perl脚本将文件名(植物名)返回为“generius\u species.png”。但是,我更希望输出这些文件名时不带.png扩展名。也就是说,我仍然希望我的grep/map表达式只查找扩展名为.png的文件名。我该怎么做?请告知。谢谢 这是我的剧本:Perl 使用grep和map查找扩展名为.png的文件名,但不输出扩展名,perl,grep,Perl,Grep,使用grep和map,我的Perl脚本将文件名(植物名)返回为“generius\u species.png”。但是,我更希望输出这些文件名时不带.png扩展名。也就是说,我仍然希望我的grep/map表达式只查找扩展名为.png的文件名。我该怎么做?请告知。谢谢 这是我的剧本: #!/usr/bin/perl use strict; use warnings; my $dir = '/Users/jdm/Desktop/xampp/htdocs/cnc/images/plants'; ope
#!/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\.png\z/.png/r } # Removes "1" from "Genus_species1.png" file names/ also finds "Genus_species.png" file names
grep { /^[^2-9]*\.png\z/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 "$file\n";
}
以下是输出:
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扩展名。您可以使用替换来删除扩展名:
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";
}
您可以使用替换删除扩展名:
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";
}
放入最后一个循环:
$file =~s/\.png//;
打印前。放入最后一个循环:
$file =~s/\.png//;
打印前。的使用简化了问题
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;
使用的方法简化了问题
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.png
⇒ xxx
和xxx.png
⇒ <代码>xxx
要实现这一点,只需更换
s/1\.png\z/.png/r
与
s/1?\.png\z//r
所以您想更改xxx1.png
⇒ xxx
和xxx.png
⇒ <代码>xxx
要实现这一点,只需更换
s/1\.png\z/.png/r
与
s/1?\.png\z//r
有趣的方法!我得试着用glob。谢谢。这应该是glob(“\Q$dir\E/*.png”)
您删除了OP对不需要的文件的过滤。有趣的方法!我得试着用glob。谢谢。应该是glob(“\Q$dir\E/*.png”)
您删除了OP对不需要的文件的过滤。