我需要在以特定模式开头的目录中搜索文件,比如“abc”。我还需要消除结果中以“.xh”结尾的所有文件。我不确定如何在 Perl 中进行操作。
我有这样的事情:
opendir(MYDIR, $newpath);
my @files = grep(/abc\*.*/,readdir(MYDIR)); # DOES NOT WORK
我还需要从结果中删除所有以“.xh”结尾的文件
谢谢,毕
尝试
@files = grep {!/\.xh$/} <$MYDIR/abc*>;
其中 MYDIR 是包含目录路径的字符串。
opendir(MYDIR, $newpath); 我的@files = grep(/abc*.*/,readdir(MYDIR)); #不工作
您将正则表达式模式与全局模式混淆了。
#!/usr/bin/perl
use strict;
use warnings;
opendir my $dir_h, '.'
or die "Cannot open directory: $!";
my @files = grep { /abc/ and not /\.xh$/ } readdir $dir_h;
closedir $dir_h;
print "$_\n" for @files;
opendir(MYDIR, $newpath) or die "$!";
my @files = grep{ !/\.xh$/ && /abc/ } readdir(MYDIR);
close MYDIR;
foreach (@files) {
do something
}
kevinadc 和 Sinan Unur 使用但未提及的一点是,readdir()
在列表上下文中调用时返回目录中所有条目的列表。然后,您可以使用任何列表运算符。这就是为什么您可以使用:
my @files = grep (/abc/ && !/\.xh$/), readdir MYDIR;
所以:
readdir MYDIR
返回 MYDIR 中所有文件的列表。
和:
grep (/abc/ && !/\.xh$/)
返回readdir MYDIR
与那里的条件匹配的所有元素。
foreach $file (@files)
{
my $fileN = $1 if $file =~ /([^\/]+)$/;
if ($fileN =~ /\.xh$/)
{
unlink $file;
next;
}
if ($fileN =~ /^abc/)
{
open(FILE, "<$file");
while(<FILE>)
{
# read through file.
}
}
}
此外,可以通过以下方式访问目录中的所有文件:
$DIR = "/somedir/somepath";
foreach $file (<$DIR/*>)
{
# apply file checks here like above.
}
或者,您可以使用 perl 模块 File::find。
而不是使用opendir
和过滤readdir
(不要忘记closedir
!),您可以使用glob
:
use File::Spec::Functions qw(catfile splitpath);
my @files =
grep !/^\.xh$/, # filter out names ending in ".xh"
map +(splitpath $_)[-1], # filename only
glob # perform shell-like glob expansion
catfile $newpath, 'abc*'; # "$newpath/abc*" (or \ or :, depending on OS)