I have a directory structure like this:

./
  whatever/
    foos_whatever.ext
  something/
    foo/
      1.ext
      2.ext
  another/
    foo.ext

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

link|improve this question
feedback

2 Answers

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.

link|improve this answer
feedback

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.

link|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
1  
For rename and prename, see their respective man pages. For subshell: stackoverflow.com/questions/5810296/… – Ignacio Vazquez-Abrams May 17 '11 at 19:54
feedback

Your Answer

 
or
required, but never shown

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