【问题标题】:How can I use File::Find to print files with the relative path only?如何使用 File::Find 打印仅具有相对路径的文件?
【发布时间】:2009-11-10 12:46:38
【问题描述】:

我在下面的代码中使用File::Find 来查找来自/home/user/data 路径的文件。

use File::Find;

my $path = "/home/user/data";
chdir($path);
my @files;

find(\&d, "$path");

foreach my $file (@files) {
print "$file\n";
}

sub d {
-f and -r and push  @files, $File::Find::name;
}

当我将 dir 路径更改为我需要从中搜索文件的路径时,它仍然为我提供了具有完整路径的文件。即

/home/user/data/dir1/file1
/home/user/data/dir2/file2
and so on...

但我想要这样的输出

dir1/file1
dir2/file2
and so on...

谁能建议我只从当前工作目录中查找文件和显示的代码?

【问题讨论】:

    标签: perl file-find


    【解决方案1】:

    以下将打印$base 下所有文件的路径,相对于$base(不是当前目录):

    #!/usr/bin/perl
    use warnings;
    use strict;
    
    use File::Spec;
    use File::Find;
    
    # can be absolute or relative (to the current directory)
    my $base = '/base/directory';
    my @absolute;
    
    find({
        wanted   => sub { push @absolute, $_ if -f and -r },
        no_chdir => 1,
    }, $base);
    
    my @relative = map { File::Spec->abs2rel($_, $base) } @absolute;
    print $_, "\n" for @relative;
    

    【讨论】:

      【解决方案2】:

      删除它怎么样:

      foreach my $file (@files) {
      $file =~ s:^\Q$path/::;
      print "$file\n";
      }
      

      注意:这实际上会改变@files的内容。

      根据 cmets 这行不通,所以让我们测试一个完整的程序:

      #!/usr/local/bin/perl
      use warnings;
      use strict;
      use File::Find;
      
      my $path = "/usr/share/skel";
      chdir($path);
      my @files;
      
      find(\&d, "$path");
      
      foreach my $file (@files) {
      $file =~ s:^\Q$path/::;
      print "$file\n";
      }
      
      sub d {
      -f and -r and push  @files, $File::Find::name;
      }
      

      我得到的输出是

      $ ./find.pl 点.cshrc 点登录 dot.login_conf 点.mailrc 点配置文件 点.shrc

      这对我来说似乎工作正常。我也用带有子目录的目录测试过,没有问题。

      【讨论】:

      • 谢谢,但它不适合我。仍在获取完整路径。
      • 是的,我已经复制并粘贴了,但它给出了 / 的完整路径。
      • 我已经在上面添加了完整的测试程序。如果这仍然不起作用,请提供您的 perl 版本和操作系统以进行进一步测试。
      • 这仍然不起作用,我使用的是 perl 5.8.8,操作系统是 Linux。但是,如果我使用 $file =~ s/$path//g;而不是 $file =~ s:^\Q$path/::;它的工作。
      • 至少你的问题解决了。我在 FreeBSD 上使用 perl 5.8.9 和 5.10.0 对此进行了测试,正则表达式没有问题。
      猜你喜欢
      • 2020-01-24
      • 1970-01-01
      • 2016-06-24
      • 2011-04-28
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多