2009-06-11 51 views
7

我需要搜索以特定模式开头的文件,例如“abc”。我还需要消除结果中以“.xh”结尾的所有文件。我不知道如何在Perl中做这件事。按模式过滤文件名

我有这样的事情:

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

我还需要消除的结果,与结尾的所有文件 “·XH”

感谢,碧

回答

7

尝试

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

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

+0

您需要将该正则表达式锚定在字符串的末尾并将其转义。不知何故(我喜欢使用角色类)。因为它是你的正则表达式匹配“abcxh.txt”。改为尝试/[.]xh$/。 – 2009-06-11 21:28:18

+0

谢谢 - 这工作! – 2009-06-11 21:42:10

+0

奇怪,我有很多问题得到这个答案格式正确 - 我没有逃过这段时间,但它不显示(除非我逃脱逃生)。此外<和>是一个斗争! 感谢您捕捉$锚,我没有测试这种情况。 固定。 – 2009-06-11 21:43:21

-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。

7

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

你正混淆了正则表达式模式和glob模式。

#!/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; 
3
opendir(MYDIR, $newpath) or die "$!"; 
my @files = grep{ !/\.xh$/ && /abc/ } readdir(MYDIR); 
close MYDIR; 
foreach (@files) { 
    do something 
} 
2

是kevinadc和思南Unur正在使用但不提的一点是,readdir()在列表环境中调用的时候返回目录中的所有条目的列表。然后你可以使用任何列表操作符。这就是为什么你可以使用:

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

所以:

readdir MYDIR 

返回MYDIR所有文件的列表。

和:

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

返回所有的元素通过readdir MYDIR符合条件那里返回。

-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) 

如果你不关心消除前缀的glob的结果$newpath ,摆脱了map+splitpath