我有一段代码可以找到给定目录中的所有.txt文件,但我不能让它查看子目录.
我需要我的脚本做两件事
例如,我有一个目录
C:\abc\def\ghi\jkl\mnop.txt
Run Code Online (Sandbox Code Playgroud)
我编写指向路径的脚本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";
}
Run Code Online (Sandbox Code Playgroud)
怎么用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);
Run Code Online (Sandbox Code Playgroud)
我相信这种解决方案更简单易读。希望对您有所帮助!
#!/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";
}
Run Code Online (Sandbox Code Playgroud)