查找文件,就地重命名 unix bash
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15007058/
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 files, rename in place unix bash
提问by ThePerson
This should be relatively trivial but I have been trying for some time without much luck. I have a directory, with many sub-directories, each with their own structure and files.
这应该是相对微不足道的,但我已经尝试了一段时间,但运气不佳。我有一个目录,有许多子目录,每个目录都有自己的结构和文件。
I am looking to find all .javafiles within any directory under the working directory, and rename them to a particular name.
For example, I would like to name all of the java files test.java.
我希望.java在工作目录下的任何目录中查找所有文件,并将它们重命名为特定名称。例如,我想将所有的 java 文件命名为test.java.
If the directory structure is a follows:
如果目录结构如下:
./files/abc/src/abc.java
./files/eee/src/foo.java
./files/roo/src/jam.java
I want to simply rename to:
我想简单地重命名为:
./files/abc/src/test.java
./files/eee/src/test.java
./files/roo/src/test.java
Part of my problem is that the paths may have spaces in them. I don't need to worry about renaming classes or anything inside the files, just the file names in place.
我的部分问题是路径中可能有空格。我不需要担心重命名类或文件中的任何内容,只需将文件名放在适当的位置即可。
If there is more than one .javafile in a directory, I don't mind if it is overwritten, or a prompt is given, to choose what to do (either is OK, it is unlikely that there are more than one in each directory.
如果.java一个目录中的文件不止一个,我不介意是否被覆盖,或者给出提示,选择做什么(要么可以,每个目录中的文件不太可能超过一个。
What I have tried:
我尝试过的:
I have looked into mvand find; but, when I pipe them together, I seem to be doing it wrong. I want to make sure to keep the files in their current location and rename, and not move.
我已经调查过mv和find;但是,当我将它们组合在一起时,我似乎做错了。我想确保将文件保留在当前位置并重命名,而不是移动。
回答by John Kugelman
The GNU version of findhas an -execdiraction which changes directory to wherever the file is.
的 GNU 版本find具有将-execdir目录更改为文件所在位置的操作。
find . -name '*.java' -execdir mv {} test.java \;
If your version of finddoesn't support -execdirthen you can get the job done with:
如果您的版本find不支持,-execdir那么您可以通过以下方式完成工作:
find . -name '*.java' -exec bash -c 'mv "" "${1%/*}"/test.java' -- {} \;
回答by dogbane
If your findcommand (like mine) doesn't support -execdir, try the following:
如果您的find命令(如我的)不支持-execdir,请尝试以下操作:
find . -name "*.java" -exec bash -c 'mv "{}" "$(dirname "{}")"/test.java' \;

