Page 1 of 1

Writing a Batch File to Move Files and Rename If Duplicate

Posted: 16 May 2013 20:50
by Benjabeanz
I have the following code for a batch file:

Code: Select all

FOR /r "D:\A B C" %%f in (*.m4a) do MOVE /-Y "%%f" "D:\X Y Z"
PAUSE


The purpose of this code is to seek out all .m4a files, regardless of their names, move them from "D:\A B C" to "D:\X Y Z" which it does all of that very well.

The issue is that, without the "/-Y" to stop it, it will automatically overwrite files of the same name. Is there a way to get it to just automatically rename the files with duplicate names (instead of just overwriting them with with no prompt) in order to prevent them from being overwritten? For example, I'd really like it if, when it runs into, say for example, File.mp3, File.mp3, and File.mp3 (Three different files, same name), it just renames them as File(1).mp3, File(2).mp3, and File(3).mp3. If anyone can provide a way to do this, I will be so grateful.

Re: Writing a Batch File to Move Files and Rename If Duplica

Posted: 16 May 2013 21:27
by foxidrive
Change "d:\abc\test 2" and "d:\test" and this should work.

Code: Select all

@echo off
set "target=d:\abc\test 2"
md "%target%" 2>nul
FOR /r "D:\test" %%a in (*.m4a) do call :next "%%a"
goto :eof
:next
set c=-1
:loop
set /a c=c+1
set num=(%c%)
if %c% EQU 0 (set num=)
if exist "%target%\%~n1%num%%~x1" goto :loop
echo processing %1
MOVE /-Y "%~1" "%target%\%~n1%num%%~x1" >nul