Perl – Using Rename to Rename Files and Directories

bashrecursiverename

I'm using the Linux rename command line tool to search recursively through a directory to rename any directories as well as files it finds. The issue I'm running into is the rename command will rename a sub-directory of a file then attempt to rename the parent directory of the same file. This will fail because the sub-directory has been renamed resulting in a "No such file or directory"

Command:

rename -f 's/foo/bar/' **
rename -f 's/Foo/Bar/' **

For example, here is an original file that I would like to replace 'foo' with 'bar'

File:

/test/foo/com/test/foo/FooMain.java

Failure:

Can't rename /test/foo/com/test/foo/FooMain.java /test/bar/com/test/foo/FooMain.java: No such file or directory

Preferred File:

/test/bar/com/test/bar/BarMain.java

You can see from the error message that it's attempting to rename the parent directory but at that point the subdirectory has already been changed resulting in the file not found error. Is there parameters for the rename command that will fix this or do I need to go about this in a different way?

Best Answer

I would go about this in a different way - specifically, using a depth-first search in place of the shell globstar **

For example, using GNU find, given:

$ tree
.
└── dir
    ├── foo
    │   └── baz
    │       └── MainFoo.c
    └── Foo
        ├── baz
        └── MainFoo.c

5 directories, 2 files

then

find . -depth -iname '*foo*' -execdir rename -- 's/Foo/Bar/;s/foo/bar/' {} +

results in

$ tree
.
└── dir
    ├── bar
    │   └── baz
    │       └── MainBar.c
    └── Bar
        ├── baz
        └── MainBar.c

5 directories, 2 files
Related Question