查找文件,将其重命名为unix bash [英] Find files, rename in place unix bash
问题描述
这应该是相对琐碎的,但是我已经尝试了一段时间没有多大的运气了.我有一个目录,其中包含许多子目录,每个子目录都有自己的结构和文件.
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.
我正在寻找工作目录下任何目录中的所有 .java
文件,并将它们重命名为特定名称.例如,我想将所有Java文件命名为 test.java
.
I am looking to find all .java
files 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
.
如果目录结构如下:
./files/abc/src/abc.java
./files/eee/src/foo.java
./files/roo/src/jam.java
我想简单地重命名为:
./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.
如果目录中有多个 .java
文件,我不介意文件是否被覆盖或给出提示以选择要执行的操作(既可以,也可以每个目录中不可能有多个目录.
If there is more than one .java
file 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.
我尝试过的事情:
我研究了 mv
和 find
;但是,当我将它们连接在一起时,我似乎做错了.我要确保将文件保留在当前位置并重命名,而不要移动.
I have looked into mv
and 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.
推荐答案
GNU版本的 find
具有 -execdir
操作,可将目录更改为文件所在的位置.
The GNU version of find
has an -execdir
action which changes directory to wherever the file is.
find . -name '*.java' -execdir mv {} test.java \;
如果您的 find
版本不支持 -execdir
,则可以通过以下方式完成工作:
If your version of find
doesn't support -execdir
then you can get the job done with:
find . -name '*.java' -exec bash -c 'mv "$1" "${1%/*}"/test.java' -- {} \;
这篇关于查找文件,将其重命名为unix bash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!