搜索+替换文件名中的字符串 [英] Search+replace strings in filenames
问题描述
使用bash,我如何在目录中以递归方式包含在所有文件名(包括文件夹)中搜索所有出现的子字符串"foo",并将其替换为"bar"?
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
运行bash脚本后,它应如下所示:
It should look like this after running the bash script:
-bar_test
- baro.txt
- xbar
- ybar.h
- 1bar.c
推荐答案
此处显示的两种变体在OPs测试结构上均可以正常使用:
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 {} +
编辑:如评论中所述,我之前使用不使用execdir
选项并使用rename
的find
命令的答案在重命名包含foo的目录中的文件时遇到问题以他们的名字.如建议的那样,我已将find命令更改为使用-execdir
,并且由于它是非标准命令,因此已使用rename
命令删除了变体.
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.
这篇关于搜索+替换文件名中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!