sub usage() { print $usage; exit } $usage = <] [substTo] Options: -i Match case insensitively -x Don't actually rename anything, just report would-be changes -y Prompt to confirm action before actually proceeding -ng Perform replacement once instead of across entire string (i.e. omit /g) -f Only rename regular files -d Only rename directories (both are renamed if neither -f or -d are specified) Parameters: mask - File mask to include in rename operation substFrom - First part of the regex: the search substTo - The second part of the regex: the replacement (null if omitted) Example - Rename html files so all "\@20" strings are replaced by spaces: rename.pl *.html "\@20" " " EODOC while ($ARGV[0] =~ /^-(.*)/) { shift; if ($1 eq 'x') { $bDontRename=1; } elsif ($1 eq 'y') { $previewAction=1; } elsif ($1 eq 'i') { $bCaseInsensitive=1; } elsif ($1 eq 'ng') { $bNotGlobal=1; } elsif ($1 eq 'f' ) { if ($onlyInclude) {usage} else {$onlyInclude = 'files'} } elsif ($1 eq 'd' ) { if ($onlyInclude) {usage} else {$onlyInclude = 'dirs'} } else {usage} } if (scalar@ARGV >= 2 && scalar@ARGV <= 3) { ($mask,$substFrom,$substTo) = @ARGV; } else {usage}; @files = glob($mask); print "Renaming ".($onlyInclude?$onlyInclude:'objects')." in '$mask' (".(scalar@files)." objects fit mask) with s/$substFrom/$substTo/".($bCaseInsensitive?'i':'').($bNotGlobal?'':'g').($bDontRename?' [SIMULATED]':'')."\n\n"; $renameCount=0; for $file (@files) { $repl=0; next if (($onlyInclude eq 'files') && !(-f $file)); next if (($onlyInclude eq 'dirs') && !(-d $file)); $newFile = $file; if (!$bCaseInsensitive && !$bNotGlobal) {$repl=1 if ($newFile =~ s/$substFrom/$substTo/g)} elsif (!$bCaseInsensitive && $bNotGlobal) {$repl=1 if ($newFile =~ s/$substFrom/$substTo/)} elsif ( $bCaseInsensitive && !$bNotGlobal) {$repl=1 if ($newFile =~ s/$substFrom/$substTo/i)} elsif ( $bCaseInsensitive && $bNotGlobal) {$repl=1 if ($newFile =~ s/$substFrom/$substTo/ig)} if ($repl) { $renameTable{$file} = $newFile; $renameCount++; } } if ($previewAction) { unless ($renameCount) { print "No files to rename.\n"; exit; } print "The following $renameCount object".($renameCount!=1?'s':'')." will be renamed:\n"; for $file (sort keys %renameTable) { $newFile = $renameTable{$file}; printf(" %-36s -> %-36s\n",$file,$newFile); } $|=1; print "\nConfirm? [y/N] "; $_ = ; unless (/^y$|^yes$/i) { print "Aborted.\n"; exit; } print "Proceeding...\n"; } for $file (sort keys %renameTable) { $newFile = $renameTable{$file}; printf(" %-36s -> %-36s\n",$file,$newFile); if (!$bDontRename) { rename $file,$newFile or die "rname.pl: $!\n"; } } print "\n"; print "$renameCount object".($renameCount!=1?'s':'')." renamed.\n";