【问题标题】:how to find duplicate file name using file:find?如何使用 file:find 查找重复的文件名?
【发布时间】:2014-05-28 19:25:00
【问题描述】:

我正在尝试编写一个程序来使用 perl 在多个驱动器中查找重复的文件名。这是我的脚本,但它提供了错误的信息。

#!/usr/bin/perl
use File::Find;
@filename;
@path;
$count;
open my $out, '>', 'output.txt' or die $!;
my $file = "E:";
find( \&edit, "$file" );

sub edit() {
    $count++;
    push( @filename, $_ );
    push( @path,     $File::Find::name );
}
print "Processing.";
for ( my $i = 0 ; $i < $count ; $i++ ) {
    for ( my $j = $i + 1 ; $j < $count ; $j++ ) {
        if ( $filename[$i] =~ /\Q$filename[$j]\E/ ) {
            print $out("$filename[$i] = $filename[$j]\n");
            print ".";
        }
    }
}

【问题讨论】:

  • 是的,但我只提到一个例子。

标签: perl perl-module


【解决方案1】:

您应该始终在每个 perl 脚本中包含 use strict;use warnings;。但是,您很幸运,这并没有导致任何错误。

事实上,除了使用正则表达式来测试您何时应该使用eq 之外,您的脚本看起来很实用。不过,作为样式更改,我会将所有路径保存在数组哈希中,以便更轻松地找到匹配的文件。尤其是目前您的方法不会将 3 个或更多组一起列出。

use strict;
use warnings;
use autodie;

use File::Find;

my %files;

open my $out, '>', 'output.txt';
my $file = "E:";

find( \&edit, "$file" );

sub edit() {
    push @{$files{$_}}, $File::Find::name;
}

while (my ($file, $paths) = each %files) {
    next if @$paths == 1;
    print "$file @$paths\n";
}

【讨论】:

  • 你能解释一下你在程序和路径中使用的push和while吗?
  • 驱动器中只能找到 pdf 或 mp3 吗?
【解决方案2】:

Kathir,模块 File::Find::Rule 非常强大且易于使用。要仅查找 mp3 文件,请执行以下操作:

#!/usr/bin/perl
use strict;
use warnings;
use File::Find::Rule;

my $directory_to_look_in = '/tmp/you/know';
my @files = File::Find::Rule->file()->name('*.mp3')->in($directory_to_look_in);

【讨论】:

  • 这是否只搜索mp3文件,我已经尝试了类型日志扩展,没有出现任何内容
  • @Venaktesan 它适用于每个扩展。也许您的文件系统在 .LOG 和 .log 之间有所不同;您可以省略 ->name(...) 来查找每个文件并查看结果
  • @files 只包含文件目录,使用它我们无法比较文件目录来查找重复文件。在 file::find 中有 "_$" 只获取文件名在 file:find:rule
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-18
  • 1970-01-01
  • 1970-01-01
  • 2013-02-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多