[oak perl] file renaming script
dbkliv
dbkliv at gmail.com
Wed Feb 16 09:23:30 PST 2005
Writing (and debugging) your own directory recursor can be pretty fun, but
if you just want something that works right away use File::Find.
Here is untested code which shows roughly how you'd convert your existing
program to use File::Find.
I've added a prompting feature to this re-write. You can turn it off
if you like,
but I really suggest running the code once or twice before letting it run wild.
When this runs, you should see something like this:
in C:\Windows\Tmp, rename foo%f.txt to foo_.txt? (y/[n]) y
in C:\Windows\Tmp, rename bar%f.txt to bar_.txt? (y/[n])
Hope this helps.
Belden
#!/usr/bin/perl
use strict;
use warnings;
use constant DO_PROMPT => 1 ;
use File::Find;
my @directories = qw( c:\windows\tmp c:\tmp ) ; # or wherever
find( \&my_rename, @directories );
sub my_rename {
my $file = $_ ; # $_ set magically by File::Find, see docs
my $newfile = $file;
$newfile =~ s/%2f/_/;
if ( DO_PROMPT ) {
print "in $File::Find::dir, rename $file to $newfile? (y/[n]) ";
chomp( my $answer = <STDIN> );
return if ! $answer; # no
response, don't do anything
return if $answer !~ /y/i ; # response
isn't 'y', don't do anything
}
if (-e $newfile) {
## warn "can't rename $file to $newfile: $newfile exists\n";
} elsif (rename $file, $newfile) {
## success, do nothing
} else {
warn "rename $file to $newfile failed: $!\n";
}
}
On Wed, 16 Feb 2005 07:13:52 -0800, Michael Paoli <mp at rawbw.com> wrote:
> In a word: recursion
>
> E.g. you could create a subroutine which handles renaming items within
> a directory, where the directory is passed to the subroutine, and where
> the subroutine, upon encountering a directory within the directory
> passed to it, calls itself (recursion), passing that (sub-)directory
> information. This will also exercise your scoping skills a bit. :-)
>
> Quoting Sandy Santra <santranyc at yahoo.com>:
>
> > I've used this script to rename directories on a Win98 machine. (Apologies
> >
> > in advance for not scoping my variables.) Is there a line of code or
> > switch or something I can add that would make it *also* operate on every
> > file within each directory it's processing? Thanks.
> >
> > ## find [text string] and delete it from all file and directory names in a
> > directory
> >
> > chdir "c:/[directoryname]" or die "cannot chdir to that directory: $!";
> > foreach $file (glob "*") {
> > $newfile = $file;
> > $newfile =~ s/%2f/_/;
> > if (-e $newfile) {
> > ## warn "can't rename $file to $newfile: $newfile
> > exists\n";
> > } elsif (rename $file, $newfile) {
> > ## success, do nothing
> > } else {
> > warn "rename $file to $newfile failed: $!\n";
> > }
> > }
>
> _______________________________________________
> Oakland mailing list
> Oakland at pm.org
> http://mail.pm.org/mailman/listinfo/oakland
>
More information about the Oakland
mailing list