Felix Nathan Hinkley
Felix Nathan Hinkley

Reputation: 37

Batch copying all files without overwriting

set dSource=C:\Games\Steam\steamapps
set dTarget=E:\Demos
set fType=*.dem

xcopy/i "%dSource%\%fType%" "%dTarget%"

This is what I currently have to copy all my files, but how can I get it to copy all the files and rename any that have the same name, so that both copies are kept in the destination folder.

Eg:
source:demo.dem
destination:demo.dem

Goes to:
destination:demo.dem, demo(1).dem

Upvotes: 3

Views: 857

Answers (2)

Endoro
Endoro

Reputation: 37569

Try this solution with copy:

@echo off &setlocal
set "dSource=C:\Games\Steam\steamapps"
set "dTarget=E:\Demos"
set "fType=*.dem"

for %%i in ("%dSource%\%fType%") do if not exist "%dtarget%\%%~nxi" (copy /b "%%~i" "%dtarget%") else call :process "%%~i"
goto :eof

:process
set /a cnt=-1
:loop
set /a cnt+=1
set "fname=%dtarget%\%~n1(%cnt%)%~x1"
if exist "%fname%" goto :loop
copy /b "%~1" "%fname%"
goto :eof

endlocal

Upvotes: 2

Magoo
Magoo

Reputation: 79947

@ECHO OFF
SETLOCAL
SET source=c:\sourcedir
SET dest=c:\destdir
SET mask=*.*
FOR /f "delims=" %%i IN (
  ' dir /b /a-d "%source%\%mask%" '
  ) DO IF EXIST "%dest%\%%i" (
  SET "destfn="
  SET "sourcefn=%source%\%%i"
  FOR /l %%g IN (1,1,9) DO IF NOT DEFINED destfn IF NOT EXIST "%dest%\%%~ni(%%g)%%~xi" SET destfn=%dest%\%%~ni(%%g^)%%~xi
  IF NOT DEFINED destfn FOR /l %%g IN (10,1,99) DO IF NOT DEFINED destfn IF NOT EXIST "%dest%\%%~ni(%%g)%%~xi" SET destfn=%dest%\%%~ni(%%g^)%%~xi
  IF NOT DEFINED destfn FOR /l %%g IN (100,1,999) DO IF NOT DEFINED destfn IF NOT EXIST "%dest%\%%~ni(%%g)%%~xi" SET destfn=%dest%\%%~ni(%%g^)%%~xi
  IF NOT DEFINED destfn FOR /l %%g IN (1000,1,9999) DO IF NOT DEFINED destfn IF NOT EXIST "%dest%\%%~ni(%%g)%%~xi" SET destfn=%dest%\%%~ni(%%g^)%%~xi
  CALL :copyg
  ) ELSE (XCOPY "%source%\%%i" "%dest%\" >nul)
)
GOTO :eof

:copyg
IF DEFINED destfn (ECHO F|XCOPY "%sourcefn%" "%destfn%" >nul
) ELSE (ECHO "%sourcefn%" NOT copied - out of generation numbers
)
GOTO :eof

WARNING: As posted, the procedure will XCOPY.

I'd suggest you change the XCOPY statements to ECHO... and >nul / ECHO F| to examine what XCOPY instructions would be generated first.

(the >nul suppresses copied messages; the ECHO F| forces XCOPY to copy to a destination FILE since there's no XCOPY switch to allow this)

Upvotes: 0

Related Questions