Copy files with a same filename within a folder structure

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
hannes2424
Posts: 2
Joined: 06 May 2010 06:08

Copy files with a same filename within a folder structure

#1 Post by hannes2424 » 06 May 2010 06:20

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

jeb
Expert
Posts: 1055
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

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

#2 Post by jeb » 06 May 2010 07:38

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

hannes2424
Posts: 2
Joined: 06 May 2010 06:08

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

#3 Post by hannes2424 » 06 May 2010 08:30

Thanks a lot! That was great help! It's working just fine :)

Post Reply