imakeitrayne
imakeitrayne

Reputation: 165

Renaming items in a File::Find folder traversal

I am supposed to traverse through a whole tree of folders and rename everything (including folders) to lower case. I looked around quite a bit and saw that the best way was to use File::Find. I tested this code:

#!/usr/bin/perl -w

use File::Find;
use strict;

print "Folder: ";
chomp(my $dir = <STDIN>);

find(\&lowerCase, $dir);

sub lowerCase{
    print $_," = ",lc($_),"\n";
    rename $_, lc($_);
}

and it seems to work fine. But can anyone tell me if I might run into trouble with this code? I remember posts on how I might run into trouble because of renaming folders before files or something like that.

Upvotes: 2

Views: 275

Answers (2)

creaktive
creaktive

Reputation: 5220

Personally, I prefer to:

  1. List files to be renamed using find dir/ > 2b_renamed
  2. Review the list manually, using an editor of choice (vim 2b_renamed, in my case)
  3. Use the rename from CPAN on that list: xargs rename 'y/A-Z/a-z/' < 2b_renamed

That manual review is very important to me, even when I can easily rollback changes (via git or even Time Machine).

Upvotes: 0

DVK
DVK

Reputation: 129569

  1. If you are on Windows, as comments stated, then no, renaming files or folders in any order won't be a problem, because a path DIR1/file1 is the same as dir1/file1 to Windows.

    It MAY be a problem on Unix though, in which case you are better off doing a recursive BFS by hand.

  2. Also, when doing system calls like rename, ALWAYS check result:

     rename($from, $to) || die "Error renaming $from to $to: $!";
    
  3. As noted in comments, take care about renaming "ABC" to "abc". On Windows is not a problem.

Upvotes: 2

Related Questions