/
prename
executable file
·142 lines (94 loc) · 2.54 KB
/
prename
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#!/usr/bin/perl
my $APP = 'prename';
our $VERSION = '0.162';
use strict;
use warnings;
use utf8;
use open qw(:std :utf8);
use encoding 'utf8';
use Getopt::Long;
use Pod::Usage;
my ($verbose, $no_act, $force);
GetOptions(
'v|verbose' => \$verbose,
'n|no-act' => \$no_act,
'f|force' => \$force,
);
my $re = shift;
if(!defined($re)) {
usage();
exit 1;
}
$verbose++ if $no_act;
if(!@ARGV) {
print "reading filenames from STDIN\n" if $verbose;
@ARGV = <STDIN>;
chomp(@ARGV);
}
my $max_len = 25;
for(sort(@ARGV)) {
my $was = $_;
eval($re);
die($@) if($@);
next if($was eq $_);
if(-e $_ and !$force) {
print STDERR "$was not renamed: $_ already exists\n";
}
elsif(($no_act) or (rename($was, $_))) {
$was = sprintf("%.25s%s", $was, length($was) > 25 ? "\e[38;5;40m...\e[m" : '');
printf("%s => %s\n", $was, $_);
# Thank you mauke ↓
#print sprintf('%*s', $max_len, $was), ' => ', $_, "\n";
# This breaks perl.vim :)
#printf("@{[ls_color(sprintf(\"%${max_len}s\", $was))]} => %s\n", ls_color($_));
}
else {
print STDERR "Can't rename $was => $_: $!\n";
}
}
sub usage {
print "$APP $VERSION\n";
pod2usage(verbose => 1);
}
=pod
=head1 NAME
rename - renames multiple files
=head1 SYNOPSIS
B<rename> S<[ B<-v> ]> S<[ B<-n> ]> S<[ B<-f> ]> I<perlexpr> S<[ I<files> ]>
=head1 DESCRIPTION
C<rename>
renames the filenames supplied according to the rule specified as the
first argument.
The I<perlexpr>
argument is a Perl expression which is expected to modify the C<$_>
string in Perl for at least some of the filenames specified.
If a given filename is not modified by the expression, it will not be
renamed.
If no filenames are given on the command line, filenames will be read
via standard input.
For example, to rename all files matching C<*.bak> to strip the extension,
you might say
rename 's/\.bak$//' *.bak
To translate uppercase names to lower, you'd use
rename 'y/A-Z/a-z/' *
=head1 OPTIONS
=over 8
=item B<-v>, B<--verbose>
Verbose: print names of files successfully renamed.
=item B<-n>, B<--no-act>
No Action: show what files would have been renamed.
=item B<-f>, B<--force>
Force: overwrite existing files.
=back
=head1 ENVIRONMENT
No environment variables are used.
=head1 AUTHOR
Larry Wall
=head1 SEE ALSO
mv(1), perl(1)
=head1 DIAGNOSTICS
If you give an invalid Perl expression you'll get a syntax error.
=head1 BUGS
The original C<rename> did not check for the existence of target filenames,
so had to be used with care. I hree I've fixed that (Robin Barker).
=cut