How to rename a file using find command
The syntax of mv
is mv <source> <target>
, so the final command that find
executes should look like:
mv test-a test-10
So, the first guess would be try:
find ~ -type f -name test-a -exec mv {} test-10 \;
However, this will fail, since {}
gets expanded to the full path and mv
is still run in the current directory, resulting in all the files being moved to your current directory and getting overwritten. To avoid this, you can use -execdir
so that mv
gets executed in the directory where the file was found:
find ~ -type f -name test-a -execdir mv {} test-10 \;
Or, since the filename is always the same:
find ~ -type f -name test-a -execdir mv test-a test-10 \;
Related videos on Youtube
Comments
-
sps over 1 year
I am trying to rename a file using
find
command.I am trying to rename file-a to file-10.
To do this I first tried below command:
sps@sps-Inspiron-N5110:~$ find ~ -type f -name test-a -exec mv test-10 '{}' ';' mv: cannot stat `test-10': No such file or directory sps@sps-Inspiron-N5110:~$
Then I tried below:
sps@sps-Inspiron-N5110:~$ find ~ -type f -name test-a -exec mv test-a test-10 '{}' ';' mv: target `/home/sps/test-a' is not a directory sps@sps-Inspiron-N5110:~$
Now I cant think how to do that with
find
. I am trying to do this withfind
, because I will have many directories with same filename, and I want to change all thetest-a
totest-10
in one command. Anyone please suggest.Thanks.
-
Eliah Kagan about 9 yearsAre all the files called exactly
test-a
(and intended to be renamed totest-10
)? Or is your goal to search for files whose names end in-a
(but may otherwise be anything) and rename them to end in-10
instead? -
sps about 9 years@EliahKagan yes, the files are exactly test-a
-
-
Fabby about 9 yearsAnd another one bows deeply to Master Muru... ;-) (Upvoted!)