I have a directory structure like this:


I want to rename all files and directories that contain foo. I would like to replace foo with bar.

Here is what I am trying:

[naomi ~/app]$ find . -name '*foo*' -exec f={} && mv -v f ${f/foo/bar} \;

This is the error I am receiving:

find: -exec: no terminating ";" or "+"

Thanks for any help :D

2 Answers 2


The obvious way I think yould be this :

find -name "*foo*" -exec rename s/foo/bar/ {} \;

or with xargs, if you have a lot of files to rename :

find -name "*foo*" | xargs -I '{}' rename s/foo/bar/ '{}'

However, the problem with that, is if you have a directory structure that looks something like this :

|-- fooDir
|   |-- foo.txt
|   `-- abc
`-- foo2

It will fail at renaming foo.txt, because it will first rename fooDir into barDir, and then claim it no longer finds "fooDir/foo.txt"

Simply re-running the command until you have no error works but it's sloppy. Another way would be to run the command in a loop, once for each level of depth of your directory tree, with the find options -mindepth and -maxdepth set to exclude other levels, but then you have to know the depth of your directory system.

I can't think of a better way.


You can't use command chains like that in -exec, since the shell interprets them as being continuations of find itself. Either run the chain in a subshell, or use rename or prename to rename the file instead.


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.