Return to Snippet

Revision: 64812
at September 22, 2013 21:52 by ff1959


Initial Code
#! /usr/bin/perl

##
## Renames files in a directory. If no directory is
## specified, the current directory is used.
##

use strict;
use warnings;
use File::Copy;
use Getopt::Long;

my $directory = "";
my $from      = "";
my $to        = "";

my $getOptionsResult=GetOptions(
    "--directory=s" => \$directory,
    "--from=s"      => \$from,
    "--to=s"        => \$to,
    );


&displayUsageAndDie if $to eq "";
&displayUsageAndDie if $from eq "";
$directory = "." if $directory eq "";


opendir(my $dh,$directory) or die "Unable to open $directory: $!";
while(readdir($dh))
{
    &renameFiles($_,$to) if m/$from/;
}
close($dh);


sub renameFiles()
{
    my $f = $_;
    chomp $f;
    (my $t = $f) =~ s/$from/$to/g;
    printf("renaming '%s' to '%s'\n",$f,$t);
    move($f, $t) or die(qq{failed to move $f -> $t});
}


sub displayUsageAndDie()
{
    print "
Renames files in a directory. If no directory is
specified, the current directory is used.

usage:
    rename --from from --to to [--directory directory]

";
    exit 1;
}

Initial URL

                                

Initial Description
Renames files in a directory. If no directory is specified, the current directory is used.

Initial Title
Rename files using perl.

Initial Tags
perl

Initial Language
Perl