3

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 with find, because I will have many directories with same filename, and I want to change all the test-a to test-10 in one command. Anyone please suggest.

Thanks.

2
  • 1
    Are all the files called exactly test-a (and intended to be renamed to test-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? Apr 4, 2015 at 4:21
  • @EliahKagan yes, the files are exactly test-a
    – sps
    Apr 4, 2015 at 5:01

1 Answer 1

10

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 \;
1
  • And another one bows deeply to Master Muru... ;-) (Upvoted!)
    – Fabby
    Apr 9, 2015 at 21:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.