Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
up vote 2 down vote accepted

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.

share|improve this answer

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.

share|improve this answer
Vasquez-Abrams, I'm not very experienced with the shell. Can you show me how this would be done? – naomi May 17 '11 at 19:48
For rename and prename, see their respective man pages. For subshell:… – Ignacio Vazquez-Abrams May 17 '11 at 19:54

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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