bash 查找并重命名目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/13039410/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find and rename a directory
提问by noway
I am trying to find and rename a directory on a linux system.
我正在尝试在 linux 系统上查找并重命名目录。
the folder name is something like : thefoldername-23423-431321
文件夹名称类似于: thefoldername-23423-431321
thefoldernameis consistent but the numbers change every time.
thefoldername是一致的,但数字每次都在变化。
I tried this:
我试过这个:
find . -type d -name 'thefoldername*' -exec mv {} newfoldername \;
The command actually works and rename that directory. But I got an error on terminal saying that there is no such file or directory.
该命令实际上有效并重命名该目录。但是我在终端上收到一个错误,说没有这样的文件或目录。
How can I fix it?
我该如何解决?
回答by John Kugelman
It's a harmless error which you can get rid of with the -depthoption.
这是一个无害的错误,您可以通过该-depth选项摆脱它。
find . -depth -type d -name 'thefoldername*' -exec mv {} newfoldername \;
Find's normal behavior is to process directories and then recurse into them. Since you've renamed it find complains when it tries to recurse. The -depthoption tells find to recurse first, then process the directory after.
Find 的正常行为是处理目录,然后递归进入它们。由于您已将其重命名,因此在尝试递归时会发现它会抱怨。该-depth选项告诉 find 先递归,然后再处理目录。
回答by Amadeu Barbosa
It's missing the -execdiroption! As stated in man pages of find:
它缺少-execdir选项!如 find 的手册页所述:
-execdir command {};
Like  -exec,  but  the  specified  command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find.
类似  -exec,但指定的命令是从包含匹配文件的子目录运行的,该目录通常不是您开始查找的目录。
find . -depth -type d -name 'thefoldername*' -execdir mv {} newfoldername \;
find . -depth -type d -name 'thefoldername*' -execdir mv {} newfoldername \;
回答by Jae-sung Park
.../ABC -> .../BCD
.../ABC -> .../BCD
find . -depth -type d -name 'ABC' -execdir mv {} $(dirname $i)/BCD \;
回答by Vilmos Kiss
With the previous answer my folders contents are disappeared.
This is my solution. It works well:
for i in find -type d -name 'oldFolderName';
do
        dirname=$(dirname "$i")
        mv $dirname/oldFolderName $dirname/newFolderName
done
使用上一个答案,我的文件夹内容消失了。
这是我的解决方案。它运作良好:
for i in find -type d -name 'oldFolderName';
do
        dirname=$(dirname "$i")
        mv $dirname/oldFolderName $dirname/newFolderName
done

