3

I want to rename folder/directory names recursively and found this solution on SO. However this command has no effect

find . -type f -exec rename 's/old/new/' '{}' \;

Is that a correct command?

Community
  • 1
  • 1
mahmood
  • 23,197
  • 49
  • 147
  • 242
  • `f` is for files. `d` for directories (folders isn't a common term for that in Unix-y context) – Mat May 23 '14 at 14:07
  • Does running the find _without_ the exec part do anything? – Mat May 23 '14 at 14:10
  • One way to check whether or not your shell script will work is to echo the command. So for example: (note that {} is not in '') `find . -type d -exec echo rename 's/a_/b_/' '{}' \;` Does the output look like what you expect? If so pipe it to shell :P – Ahmed Masud May 23 '14 at 14:32
  • could just use a loop instead `for f in $( find . -type f -name "*a*" ); do mv $f $(basename $f | sed "s/a/b/") ; done` –  May 23 '14 at 14:49
  • @Jidder: Still no effect. Have you test that? – mahmood May 23 '14 at 14:56
  • Yep, works for me ? What problem are you having with it ? Is there an error ? –  May 23 '14 at 14:59
  • `for f in $( find . -type f -name "*b_*" ); do mv $f $( dirname $f)/$(basename $f | sed "s/b_/a_/") ; done` forgot to leave the original directory there. That should work recursively now. –  May 23 '14 at 15:11

1 Answers1

5
find . -depth -name '*a_*' -execdir bash -c 'mv "$0" "${0//a_/b_}"' {} \;

The -depth switch is important so that the directory content is processed before the directory itself! otherwise you'll run into problems :).

100% safe regarding filenames with spaces or other funny symbols.

gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104