Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursively rename directories in bash

Tags:

bash

I'd like to recursively rename all directories containing the string foo by replacing that part of the string with Bar. I've got something like this so far, but it doesn't quite work. I'd also like foo to be searched case-insensitive.

find . -type d -exec bash -c 'mv "$1" "${1//foo/Bar}"' -- {} \;

Are there any elegant one-liners that might be better than this attempt? I've actually tried a few but thought I'd defer to the experts. Note: i'm doing this on a Mac OS X system, and don't have tools like rename installed.

like image 822
Poe Avatar asked Oct 18 '12 01:10

Poe


1 Answers

Try the following code using parameter expansion

find . -type d -iname '*foo*' -depth -exec bash -c '
    echo mv "$1" "${1//[Ff][Oo][Oo]/BAr}"
' -- {} \;

But your best bet will be the prename command (sometimes named rename or file-rename)

find . -type d -iname '*foo*' -depth -exec rename 's@Foo@Bar@gi' {} +

And if you are using bash4 or zsh (** mean recursive):

shopt -s globstar
rename -n 's@Foo@Bar@gi' **/*foo*/

If it fit your needs, remove the -n (dry run) switch to rename for real.

SOME DOC

rename was originally written by Perl's dad, Larry Wall himself.

like image 196
14 revs, 3 users 97% Avatar answered Nov 08 '22 18:11

14 revs, 3 users 97%