Using Perl rename to rename files and directories

I’m using the Perl 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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x