user1778985
user1778985

Reputation:

Windows Batch file to copy certain file types from subdirectories to one folder with rename

I had tried to make a batch script that copies all *.mpg files located in G:(random named subfolders here)\000.mpg to E:\PVR.

for /R g:\ %%f in (*.mpg) do copy %%f E:\PVR\

the problem is that source file names are the same, while they are different files with same name in all subfolders. the script overwrites the previous file and so I only have the last file after batch copy. please help me rename copied files with a counter or something.

Upvotes: 2

Views: 7286

Answers (1)

dbenham
dbenham

Reputation: 130809

This should do the trick.

@echo off
setlocal disableDelayedExpansion
set "src=."
set "dest=\temp"
set mask=*.mpg
for /r "%src%" %%F in (%mask%) do (
  if exist "%dest%\%%~nxF" (call :copyDup "%%F") else copy "%%F" "%dest%" >nul
)
exit /b

:copyDup
set /a cnt=1
:loop
set /a cnt+=1
if exist "%dest%\%~n1(%cnt%)%~x1" goto :loop
copy %1 "%dest%\%~n1(%cnt%)%~x1" >nul
exit /b

Upvotes: 6

Related Questions