Perl通过所有子目录找到一个基于它的扩展名的文件

Heu*_*tic 3 perl

我有一段代码可以找到给定目录中的所有.txt文件,但我不能让它查看子目录.

我需要我的脚本做两件事

  1. 浏览文件夹及其所有子目录以查找文本文件
  2. 打印出其路径的最后一段

例如,我有一个目录

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)

Tim*_*own 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);
Run Code Online (Sandbox Code Playgroud)


Tk4*_*421 5

我相信这种解决方案更简单易读。希望对您有所帮助!

#!/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)