8

我需要在以特定模式开头的目录中搜索文件,比如“abc”。我还需要消除结果中以“.xh”结尾的所有文件。我不确定如何在 Perl 中进行操作。

我有这样的事情:

opendir(MYDIR, $newpath);
my @files = grep(/abc\*.*/,readdir(MYDIR)); # DOES NOT WORK

我还需要从结果中删除所有以“.xh”结尾的文件

谢谢,毕

4

6 回答 6

7

尝试

@files = grep {!/\.xh$/} <$MYDIR/abc*>;

其中 MYDIR 是包含目录路径的字符串。

于 2009-06-11T21:18:07.707 回答
7

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;
于 2009-06-11T21:20:15.063 回答
3
opendir(MYDIR, $newpath) or die "$!";
my @files = grep{ !/\.xh$/ && /abc/ } readdir(MYDIR);
close MYDIR;
foreach (@files) { 
   do something
}
于 2009-06-11T21:31:24.693 回答
2

kevinadc 和 Sinan Unur 使用但未提及的一点是,readdir()在列表上下文中调用时返回目录中所有条目的列表。然后,您可以使用任何列表运算符。这就是为什么您可以使用:

my @files = grep (/abc/ && !/\.xh$/), readdir MYDIR;

所以:

readdir MYDIR

返回 MYDIR 中所有文件的列表。

和:

grep (/abc/ && !/\.xh$/)

返回readdir MYDIR与那里的条件匹配的所有元素。

于 2009-06-11T21:40:19.540 回答
-1
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。

于 2009-06-11T21:07:26.483 回答
-1

而不是使用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)

如果您不关心消除$newpath结果的前缀glob,请去掉map+splitpath.

于 2009-06-12T17:45:58.613 回答