This snippet will allow you to rename all the files of a given type in a specific directory. This example will rename all the files that end in '.pl' so that they end in '.pl.bak'. Generalised as suggested by Chady Added overwrite prompt as suggested by AltBlue
my $dir = 'c:/'; my $from = '.pl'; my $to = '.pl.bak'; while (<$dir*$from>) { my ($old,$new); $old = $new = $_; $new =~ s/$from$/$to/; next if $old eq $new; unless (exist($new)) { rename $old, $new and print "Renamed $old $new\n"; } } sub exist { my $file = shift; if (-e $file) { print "File $file exists, owerwrite (y/n) "; return (<> =~ m/^y/i) ? 0 : 1 } return 0; }

Replies are listed 'Best First'.
Re: Renaming Files
by blakem (Monsignor) on Jul 14, 2001 at 02:10 UTC
Re: Renaming Files
by AltBlue (Chaplain) on Jul 13, 2001 at 02:28 UTC
    hm, this is a very weary topic...
    what i first notice is that your solution overwrites any already existent foo.pl.bak in that directory :(

    a more general/recursive approach in a oneliner may be: find2perl . -depth -eval 'my $o = $_; s/\.pl$/$&.bak/ and -e or rename $o, $_' | perl -w

    ... or a 'rewriting' or your code:

    #!/usr/bin/perl -w use strict; use File::Find; my ($dir, $in, $out) = @ARGV; File::Find::finddepth( { wanted => sub { my $o = $_; s/$in/$out/ or return; -e or rename $o, $_; } }, $dir );

    heh, this latter version suffers ofc of limitation such as:
    ./kk.pl . '\.pl$' '$&.bak' ... which will not result in renaming 'foo.pl' to 'foo.pl.bak' but to 'foo$&.bak' :)

    idea: do an engine to make possible specification of any 'substitution' pattern from the command line ;-)

    --
    AltBlue.

Re: Renaming Files
by Chady (Priest) on Jul 11, 2001 at 16:44 UTC

    I like to make that of further use without having to edit the source each time, so I added a bit at it:

    print 'Enter folder for renaming: '; chomp(my $dir=<STDIN>); print 'rename from *.'; chomp(my $from=<STDIN>); print 'rename to *.'; chomp(my $to=<STDIN>); $dir .= '/' unless ($dir =~ /[\/]$/); while (<$dir*.$from>) { my ($old,$new); $old = $new = $_; $new =~ s/$from$/$to/; rename $old, $new; }

    He who asks will be a fool for five minutes, but he who doesn't ask will remain a fool for life.

    Chady | http://chady.net/