35

I need to assemble a lot of images into one directory. Many of those images have the same file names.

Is there some safe version of mv that will automatically rename files if the target filename already exists so that pic1.jpeg becomes something like pic1_2.jpeg?

I could write my own python script but there has to be something like this out there so I can do:

find . -type f -name *.jpg -exec mvsafe '{}' /targetpath/ \;

2 Answers 2

53

mv already supports this out of the box (at least in Debian):

mv --backup=t <source_file> <dest_file>

As seen in mv(1) manpage:

--backup[=CONTROL]
         make a backup of each existing destination file

The  backup  suffix  is  `~',  unless  set  with   --suffix   or   SIM‐
PLE_BACKUP_SUFFIX.   The version control method may be selected via the
--backup option or through the  VERSION_CONTROL  environment  variable.

To make --backup=t mean "make numbered backups", invoke as follows:

env VERSION_CONTROL=numbered mv --backup=t <source_file> <dest_file>

(dest_file can of course be a directory).

Edit: in later versions (at least GNU coreutils 8.22 but prolly already much earlier) you can simply write

mv --backup=numbered <source_file> <dest_file>
7
  • 2
    +1 for an amazingly clean solution. BTW the option is present on RHEL 6 too. Commented May 7, 2011 at 12:32
  • While nice functionality, this does not really help that much in my case since it will append the suffix after the extension, so the files will end up with names like .jpg~1~ while I would need them to be named _1.jpg. I will probably use mmv to rename the files after moving them.
    – theduke
    Commented May 7, 2011 at 16:11
  • 5
    this is the mmv command that will achieve my desired result after doing mv --backup=numbered: mmv -v "..~*~" "#1_#3.#2"
    – theduke
    Commented May 7, 2011 at 16:21
  • On my Debian system (mmv 1.01b-18), the correct mmv command is: mmv -v "*.*~*~" "#1_#3.#2"
    – Xavier
    Commented Jun 19, 2015 at 9:12
  • Works on Kubuntu 20.10 as mv --backup=numbered <source> <dest> but isn't documented in the man page.
    – pbhj
    Commented Nov 19, 2020 at 20:00
0

move command rename file if file exists.

Install

node install -g @gauravnumber/move

Example

move *.jpg dirname

link to repo

2
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Aug 3, 2022 at 10:30
  • This is not what is expected from all "move" program (and in Windows it does behave like in Linux). This is unexpected, it should be an option, not the default behavior. Commented Sep 29, 2022 at 14:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .