Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find files, rename in place unix bash

Tags:

bash

unix

rename

mv

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 .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.

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 .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.

What I have tried:

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.

like image 348
ThePerson Avatar asked Feb 21 '13 16:02

ThePerson


People also ask

How do I search for a filename in Unix?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in.

How do I search for and rename a file in Linux?

Renaming files on Linux systems is usually handled by the mv (move) command. The syntax is just mv old. txt new. txt .

How do I search for a file in bash?

You need to utilize the “-L” option and the path and “-name” option in your command. The “*” in the name specification is used for searching “all” the bash files with “.


2 Answers

The GNU version of find has an -execdir action which changes directory to wherever the file is.

find . -name '*.java' -execdir mv {} test.java \;

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' -- {} \;
like image 165
John Kugelman Avatar answered Oct 11 '22 23:10

John Kugelman


If your find command (like mine) doesn't support -execdir, try the following:

find . -name "*.java" -exec bash -c 'mv "{}" "$(dirname "{}")"/test.java' \;
like image 44
dogbane Avatar answered Oct 11 '22 23:10

dogbane