mv, rename if exists
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/ \;
Solution 1:
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>