how to find duplicate file name using file:find?

2019-08-29 10:41发布

I am trying to write a program to find duplicate file names in multiple drive using perl. This is my script, but it gives wrong info.

#!/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 ".";
        }
    }
}

2条回答
Explosion°爆炸
2楼-- · 2019-08-29 11:08

Kathir, the module File::Find::Rule is pretty powerful and easy to use. To find only mp3 files do this:

#!/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);
查看更多
\"骚年 ilove
3楼-- · 2019-08-29 11:22

You should always include use strict; and use warnings; in EVERY perl script. However, you lucked and that didn't lead to any errors.

In fact, other than using a regex to test when you should've used eq, your script looks functional. As a style change though, I would've saved all paths in a hash of arrays to more easily find matching files. Especially as currently your method wouldn't list groups of 3 or more together.

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";
}
查看更多
登录 后发表回答