#!/usr/bin/perl -w # # Rename files by substituting 'from' to 'to' for all specified files. # # Chad use strict; use File::Basename; use Getopt::Long; my $version = 2006.027; my $help = undef; my $verbose = undef; my $pretend = undef; my $overwrite = undef; # Parse command line arguments Getopt::Long::Configure("bundling"); my $getoptsret = GetOptions ( 'help|h' => \$help, 'verbose|v+' => \$verbose, 'pretend|p' => \$pretend, 'overwrite|o' => \$overwrite, ); if ( ! $getoptsret || defined $help || $#ARGV < 2 ) { my $basename = basename $0; print "$basename ($version), a Perl based rename\n\n"; print "Usage: $basename [-v] \n\n"; print " -v,verbose Be more verbose\n"; print " -p,pretend Do everything except make changes\n"; print " -o,overwrite Attempt to overwrite existing files for collisions\n"; print "\n"; print "The substitution is done with regular expressions, this means that\n"; print "the end of line can be selected with '\$' and the beginning with '^'.\n"; print "Adding a suffix to file names: prename \$ .txt *\n"; print "Adding a prefix to file names: prename ^ DD *\n"; print "\n"; exit (1); } my $from = shift @ARGV; my $to = shift @ARGV; my $count = 0; foreach my $file (@ARGV) { # Skip if nothing in the name can be replaced next if ( $file !~ /$from/ ); my $newfile = $file; $newfile =~ s/$from/$to/; # Skip if no name change would occur next if ( $file eq $newfile ); if ( $verbose ) { print "Renaming $file -> $newfile\n"; } # Check if a file by the new name exists if ( -e "$newfile" && ! defined $overwrite ) { print "Name collision: file '$newfile' already exists, skipping\n"; next; } # If not pretending rename the file otherwise incriment the counter if ( ! defined $pretend ) { if ( rename ("$file", "$newfile") ) { $count++; } else { print "Error renaming $file\n"; } } else { $count ++; } } if ( $verbose ) { if ( $pretend ) { print "Would have renamed $count files\n"; } else { print "Renamed $count files\n"; } }