Perl script to rename a bunch of directories recursively

#!/usr/bin/perl

my %repTable = (

'Original Folder Name' => 'New Folder Name',

'Original Folder Name' => 'New Folder Name',

'Original Folder Name' => 'New Folder Name',

'Original Folder Name' => 'New Folder Name',

'Original Folder Name' => 'New Folder Name'

);

foreach my $k (keys(%repTable)) {

print "Rename $k => $repTable{$k}n";

print "Find ...n";

my @finds = `find . -type d -name '$k'`;

foreach my $find (@finds) {

chomp $find;

my $repl = $find;

$repl =~ s/$k/$repTable{$k}/;

print "Rename $find => $repln";

system("mv '$find' '$repl'");

}

}

Or rename and move contents for any folder where new folder name already exists

#!/usr/bin/perl

my %repTable = (

'Original Folder Name' => 'New Folder Name',

'Original Folder Name' => 'New Folder Name',

'Original Folder Name' => 'New Folder Name',

'Original Folder Name' => 'New Folder Name',

'Original Folder Name' => 'New Folder Name'

);

foreach my $k (keys(%repTable)) {

print "Rename $k => $repTable{$k}n";

print "Find ...n";

my @finds = `find . -type d -name '$k'`;

foreach my $find (@finds) {

chomp $find;

my $repl = $find;

$repl =~ s/$k/$repTable{$k}/;

if (-e $repl) {

print "Sync $find => $repln";

system("rsync -a --progress '$find/' '$repl/'");

print "Remove $findn";

system("rm -rf '$find'");

} else {

print "Rename $find => $repln";

system("mv '$find' '$repl'");

}

}

}

Or if there are parenthesis in any of the source folder names...

my %repTable = (

'Original Folder (Name)' => 'New Folder Name',

'Original Folder (Name)' => 'New Folder Name',

'Original Folder Name' => 'New Folder Name',

'Original Folder Name' => 'New Folder Name',

'Original Folder Name' => 'New Folder Name'

);

foreach my $k (keys(%repTable)) {

print "Rename $k => $repTable{$k}n";

print "Find ...n";

my @finds = `find . -type d -name '$k'`;

foreach my $find (@finds) {

chomp $find;

my $repl = $find;

my $fk = $k;

$fk =~ s/(/\(/g;

$fk =~ s/)/\)/g;

$repl =~ s/$fk/$repTable{$k}/;

if (-e $repl) {

print "Sync $find => $repln";

system("rsync -a --progress '$find/' '$repl/'");

print "Remove $findn";

system("mv '$find' '$find.old'");

} else {

print "Rename $find => $repln";

system("mv '$find' '$repl'");

}

}

}

No comments: