develooper Front page | | Postings from March 2006

Re: file renamer (i'm a newbie)

Thread Previous | Thread Next
Eric Waguespack
March 24, 2006 22:07
Re: file renamer (i'm a newbie)
Message ID:
You are really helpful... thanks for all the info.

here is my latest code... now l'll take a few minutes to digest your

use strict;
use warnings;
use diagnostics;
use File::Find;

finddepth(\&fixnames, ".");

sub fixnames
   # do not rename dotfiles
   return if /^\./;
   # do not rename this system directory
   return if /lost\+found/;
   # preserve original name
   my $old = $_ ;
   # preserve new name, and lowercase it at the same time
   my $new = lc $old ;
   # translate all characters to _ except 'a-z 0-9 . _'
   $new =~ tr/a-z0-9._/_/c;
   # remove all leading _'s
   $new =~ s/^_+//;
   # fix odd extensions
   $new =~ s/\.mpeg$/\.mpg/;
   $new =~ s/\.ram$/\.rm/;
   $new =~ s/\.qt$/\.mov/;
   $new =~ s/\.jpeg$/\.jpg/;
   # replace _. with .
   $new =~ s/_\./\./g;
   # replace ._ with _
   $new =~ s/\._/_/g;
   # squeeze repeated _'s
   $new =~ tr/__//s;
   # squeeze repeated .'s
   $new =~ tr/..//s;
   # abort if filname has not changed
   return if $new eq $old;
   # abort if new name already exists (i would like to change
increment the file and try again somehow)
   return if (-e $new);
   # I wonder if I should do something like --> rename($was, $_)
unless $was eq $old;
  rename($old, $new) or warn "Cannot rename $old:$!\n";
   # show the files that we are renaming
   print "renaming \n $File::Find::name ---> \n $File::Find::dir/$new\n";

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About