Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

bash - Search+replace strings in filenames

Using bash, how can I search for all occurrences of the substring 'foo' in all filenames (including folders) contained recursively in a directory and replace them them with 'bar'?

For example, if the current structure looks like:

-foo_test
    - fooo.txt
    - xfoo
        - yfoo.h
- 1foo.c

It should look like this after running the bash script:

-bar_test
    - baro.txt
    - xbar
        - ybar.h
- 1bar.c
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Both variations shown here using work correctly on OPs test structure:

find . -depth -name '*foo*' -execdir bash -c 'mv -i "$1" "${1//foo/bar}"' bash {} ;

or, if you have a very large number of files and want it to run faster:

find . -depth -name '*foo*' -execdir bash -c 'for f; do mv -i "$f" "${f//foo/bar}"; done' bash {} +

EDIT: As noted in the comments, my earlier answer using a find command that did not use the execdir option and using rename has problems renaming files in directories that contain foo in their name. As suggested, I have changed the find commands to use -execdir, and I have deleted the variation using the rename command since it is a non-standard command.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...