我有一段代码可以找到给定目录中的所有.txt文件,但我无法查看子目录。
我需要我的脚本做两件事
例如,我有一个结构目录
C:\abc\def\ghi\jkl\mnop.txt
我指向路径C:\abc\def\
的脚本。然后,它会遍历每个子文件夹,找到mnop.txt
以及该文件夹中的任何其他文本文件。
然后打印出ghi\jkl\mnop.txt
我正在使用它,但它实际上只打印出文件名,如果文件当前在该目录中。
opendir(Dir, $location) or die "Failure Will Robertson!";
@reports = grep(/\.txt$/,readdir(Dir));
foreach $reports(@reports)
{
my $files = "$location/$reports";
open (res,$files) or die "could not open $files";
print "$files\n";
}
答案 0 :(得分:6)
如何使用File::Find
?
#!/usr/bin/env perl
use warnings;
use strict;
use File::Find;
# for example let location be tmp
my $location="tmp";
sub find_txt {
my $F = $File::Find::name;
if ($F =~ /txt$/ ) {
print "$F\n";
}
}
find({ wanted => \&find_txt, no_chdir=>1}, $location);
答案 1 :(得分:4)
我相信这个解决方案更简单易读。我希望它有用!
#!/usr/bin/perl
use File::Find::Rule;
my @files = File::Find::Rule->file()
->name( '*.txt' )
->in( '/path/to/my/folder/' );
for my $file (@files) {
print "file: $file\n";
}
答案 2 :(得分:2)
如果你只使用File::Find
核心模块,那就容易多了:
#!/usr/bin/perl
use strict;
use warnings FATAL => qw(all);
use File::Find;
my $Target = shift;
find(\&survey, @ARGV);
sub survey {
print "Found $File::Find::name\n" if ($_ eq $Target)
}
第一个参数:要搜索的文件的无路径名称。所有后续参数都是要检查的目录。 文件::递归查找搜索,因此您只需要命名树的顶部,也会自动搜索所有子目录。
$File::Find::name
是文件的完整路径名,因此如果您想要相对路径,可以从中减去$location
。