-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnormtrknum
70 lines (64 loc) · 2.17 KB
/
normtrknum
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
67
68
69
70
#!/usr/bin/env perl
#
# stupid little script that formats a track-number prefix just the way I like it:
# [#.]##-title.ext
#
# 20210529 klg wrote
#
use strict;
use warnings;
use English;
use Cwd;
use Getopt::Std;
our ($opt_n,$opt_r,$opt_t,$opt_x);
getopts( "nrtx" ); # -n Noop mode; -r Recurse; -x only modify things that have an eXtension
use File::Find qw( find );
sub newnm { my ($nm) = @_;
# since '.' leads ext, trknum+title regex can match with title eq ext, resulting in '.' that leads ext being replaced with '-'
my ($fnm,$ext) = $nm =~ m/^(.*)(\.[^.]+)$/; # to avoid, rmv ext from value that is tested against trknum+title regex ...
$fnm = $nm unless $fnm || $opt_x;
return unless $fnm;
my $origfnm = $fnm;
if( $fnm =~ m!^ # $ext &&
(?<trknum>
(?: \d\. )? # leading 2. is a flattening of "DISC 2/"; include in trknum
\d{2,} # I've almost never seen a mp3 or flac track that did not have a 2-digit track number...
)
[-\s.]+ # what we want to replace with a single '-'; could almost be "punct"
(?<title> .* )$
!x
) {
$fnm = $+{trknum} . '-' . $+{title} . ($ext || '');
}
if( $opt_t ) { # make title-fixing mods?
$fnm =~ s![\s_]\-[\s_]!-!g;
$fnm =~ s!_! !g;
$fnm =~ s!\s+! !g;
}
return $fnm if $origfnm ne $fnm;
}
sub wanted { # https://perldoc.perl.org/File::Find#$File::Find::dir-is-the-current-directory-name,
my ($root) = @_; # note coupling of File::Find::var* (and $_) content with no_chdir value!!!
# print "$File::Find::name X-X $_\n";
$File::Find::prune = 1 # Don't recurse.
unless $opt_r || $File::Find::name eq $root;
my $dn = $File::Find::dir;
my $nm = $_;
if( -f $nm ) { # print "F: $dn/$nm\n";
my $newnm = newnm( $nm );
if( $newnm ) {
if( $opt_n ) {
print "mv '$dn/$nm' '$dn/$newnm'\n"
}
else {
print "mv '$dn/$newnm' '$dn/$nm'\n"; # undo/reversing command
rename( "$nm", "$newnm" ) or die "renaming $dn/$nm -> $dn/$newnm\n";
}
}
}
}
my $root = '.';
find({
wanted => sub { wanted($root); },
no_chdir => 0,
}, $root);