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"


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'




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

Preferred File:


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?

  • They are separate lines running in a bash script. Would it act differently if I had combined them like your example? – Bobbake4 May 23 '17 at 14:21

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


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
  • Depth first really is the way to go. – l0b0 May 23 '17 at 14:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.