#21 Mass File Renaming

The standard Unix/Linux rename command allows you to change the name of only one file at a time. (You can move multiple files from one directory to another but only really rename one.) If you want to rename multiple files at one time, you'll need a Perl script.

The Code

 1 #!/usr/bin/perl 2 use strict; 3 use warnings; 4 5 use Getopt::Std; 6 use vars qw/$opt_n $opt_v $opt_e/; 7 8 if (not getopts("nve:")) { 9 die("Bad options"); 10 } 11 if (not defined($opt_e)) { 12 die("Required option -e missing"); 13 } 14 15 foreach my $file_name (@ARGV) 16 { 17 # Compute the new name 18 my $new_name = $file_name; 19 20 # Perform the substitution 21 eval "\$new_name =~ s$opt_e"; 22 23 # Make sure the names are different 24 if ($file_name ...

Get Wicked Cool Perl Scripts now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.