Page 1 of 1

Copy files with a same filename within a folder structure

Posted: 06 May 2010 06:20
by hannes2424
Hey folks!

I searched through the web but I could not find anything helping me.
I'm trying to write a batch file in order to copy JUST the files within a folder structure to another folder.
All the files within the given folder structure do have the same name, but I don't want the batch script to overwrite the file that has been copied into the destination directory so far, instead it should in a way rename the files, so that in the end I do not have only one file called "filename.dat" but all of the files out of the source directory called "filename01.dat", "filename02.dat"... or something similar...

This is what I have got so far:

Code: Select all

@echo off

Set "sourceDir=%CD%

:: copy files
For /F "Delims=" %%! in ('Dir "%sourceDir%\" /b /s /a-d 2^>nul') do (
   @xcopy "%%!" "%sourceDir%\%z%" /i /y /h /f /c
   
)
pause


I am able to get the single files within the folder structure, but I don't really know how to manage the overwriting problem. (The first file is copied and is then overwritten because of the next file which has the exact same filename)

Hope you can help me!

Greetings, hannes2424

Re: Copy files with a same filename within a folder structur

Posted: 06 May 2010 07:38
by jeb
Hi hannes2424,

you can use a counter, like here

Code: Select all

@echo off
setlocal EnableDelayedExpansion EnableExtensions

Set "sourceDir=%CD%\pp"
set z=newfilename
set ext=.bak

:: copy files
rem set the count to a big number for easy format it
set count=10000
For /F "delims=" %%f in ('Dir "%sourceDir%\" /b /s /a-d 2^>nul') do (
   set /a count+=1
    xcopy "%%f" "%sourceDir%\%z%!count:~-2!%ext%" /y /h /f /c
)
goto :eof



if you only want to number the files when a file with that name exists, than you should use a function like
:copyAndRename <source> <dest>
step1:
check if <dest> exists
if it exists append a counter, beginning with 01

step2:
if that file exists also, increment the counter, goto step2

step3:
copy the file
return to the loop

jeb

Re: Copy files with a same filename within a folder structur

Posted: 06 May 2010 08:30
by hannes2424
Thanks a lot! That was great help! It's working just fine :)