How to rename a file using find command

13,514

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 \;
Share:
13,514

Related videos on Youtube

sps
Author by

sps

got to know more...

Updated on September 18, 2022

Comments

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

    • Eliah Kagan
      Eliah Kagan about 9 years
      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?
    • sps
      sps about 9 years
      @EliahKagan yes, the files are exactly test-a
  • Fabby
    Fabby about 9 years
    And another one bows deeply to Master Muru... ;-) (Upvoted!)