Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

share|improve this question
add comment

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.

share|improve this answer
add comment

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
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
add comment

Your Answer

 
discard

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.