-
Notifications
You must be signed in to change notification settings - Fork 34
/
md5_rename.pl
66 lines (49 loc) · 1.33 KB
/
md5_rename.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/perl
# Rename files to their MD5 hex value in a given directory (and its subdirectories).
# Example:
# "IMG_20231024_094115.jpg" becomes "571b4ba928ae62e103b54727721ebe56.jpg"
use 5.036;
use Digest::MD5 qw();
use File::Find qw(find);
use File::Basename qw(dirname basename);
use File::Spec::Functions qw(catfile);
sub md5_rename_file ($file) {
open my $fh, '<:raw', $file or return;
my $ctx = Digest::MD5->new;
$ctx->addfile($fh);
my $digest = $ctx->hexdigest;
close $fh;
my $dirname = dirname($file);
my $basename = basename($file);
if ($basename =~ s{^.*\.(\w+)\z}{$digest.$1}s) {
## ok
}
else {
$basename = $digest;
}
my $new_file = catfile($dirname, $basename);
if (-e $new_file) { # new file already exists
return;
}
rename($file, $new_file) or return;
return $basename;
}
my @dirs = @ARGV;
@dirs || die "usage: $0 [files | dirs]\n";
find(
{
wanted => sub {
if (-f $_) {
say ":: Renaming file: $_";
my $basename = md5_rename_file($_);
if (defined($basename)) {
say "-> renamed to: $basename";
}
else {
say "-> failed to rename...";
}
}
},
},
@dirs
);