Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

recursively rename directories in 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...