Take the 2-minute tour ×

I need to recursively rename every file and directory. I convert spaces to underscores and make all file/directory names to lowercase. How can I make the following script rename all files in one run? Currently the script needs to be run several times before all the files/directories are converted. The code is below:


use File::Find;

$input_file_dir = $ARGV[0];

sub process_file {
        print "file/dir name: $clean_name\n";
find(\&process_file, $input_file_dir);
share|improve this question
What should happen if "Some Filename" and "some_filename" both exist in the same directory? And for non-empty directories "Some Dir" and "some_dir" with the same parent? –  Jim Lewis Mar 31 '10 at 23:35
Do you know that perl comes with a rename(3) script? –  Pasi Savolainen Mar 31 '10 at 23:50
@Pasi: it is "prename". For some reason, as usual, Debian decided to break things around and rename it to "rename", replacing the original rename from userlinux. –  Juliano Apr 1 '10 at 17:45

3 Answers 3

up vote 3 down vote accepted

You either need to specify bydepth => 1 in the options you pass to find or call finddepth. From perldoc File::Find:



However, you still need to decide how to deal with naming clashes because rename will clobber the target if the target exists.


use strict; use warnings;
use File::Find;

finddepth(\&process_file, $_) for @ARGV;
share|improve this answer

if you are open to other approaches, here's a Python solution

import os
for R,DIR,FILES in os.walk("/mypath",topdown=False):
    for file in FILES:
        newfile=file.lower().replace(" ","_")
        os.rename( os.path.join(R,file) , new_file_name)
    for dir in DIR:
        newdir=dir.lower().replace(" ","_")
        os.rename( os.path.join(R,dir) , new_dir_name)
share|improve this answer
I used the above script and I see that it works perfectly fine. Thanks for sharing this :) –  Horizon Jul 12 '13 at 20:04

You can rename files before traversing through a directory.

        preprocess => sub {
            for (@_) {
                my $oldname = $_;
                $_ = lc;
                rename $oldname => $_;
            return @_;
        wanted => sub {
            print "$File::Find::name was already renamed\n";

Or you could delay the renames until after traversal has occurred.

finddepth(sub {
        print "in $File::Find::dir, renaming $_\n";
        my $newname = lc;
        $newname =~ s/\s/_/g;
        rename $_ => $newname;

The problem you are encountering is because

find finds directory "Abc Def"
find calls wanted("Abc Def")
    rename "Abc Def" => "abc_def"
find tries to enter "Abc Def", which does not exist anymore
    so everything underneath does not get processed

share|improve this answer

Your Answer


