develooper Front page | perl.golf | Postings from March 2006

Re: file renamer (i'm a newbie)

Thread Previous | Thread Next
From:
Eric Waguespack
Date:
March 24, 2006 22:07
Subject:
Re: file renamer (i'm a newbie)
Message ID:
1c246150603242207u67bb29acm77182e90f5c4c011@mail.gmail.com
You are really helpful... thanks for all the info.

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

#!/usr/bin/perl
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


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About