1.

Solve : Batch - Copy files with a same filename within a folder structure?

Answer»

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]@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, hannes2424Quote from: hannes2424 on May 06, 2010, 06:24:39 AM


"All the files within the given folder structure do have the same name."Code: [Select])


There are never two files with same name in the same folder.Are you still interested in this?

I happen to be WORKING on a project which is related and might help you out.

Pleas give more details on what you are trying to achieve.

What type of files, etc...?

[emailprotected]If understand this correctly, you have duplicate file names across a directory tree but now you want them in a single directory where duplicate file names can be a real problem.

One solution would be to use XCOPY as a helper utility (use the /s switch to hunt down all the files in the tree, but also use the /l switch to not actually copy anything. Th end result will be a list of files that would have been copied which you can use in combination with an existence test and the plain old COPY utility. Along the way you can build a sequence number to add to the file name to prevent duplicates. A bit unconventional perhaps, but sound logic.

Code: [Select]@echo off
setlocal
set source=i:\myFiles
set target=c:\temp

for /f "tokens=*" %%i in ('xcopy /s /e /l %source%\* %target%') do (
if exist %target%\%%~ni%%~xi (call :sequence %%i) else (copy "%%i" "%target%\%%~ni%%~xi" 1>nul 2>nul)
)
goto :eof

:sequence
for /l %%x in (1,1,25) do (
if not exist "%target%\%~n1_%%x%~x1" (
copy "%%i" "%target%\%~n1_%%x%~x1" 1>nul 2>nul
goto :eof
)
)
goto :eof

Be sure to set the source and target variables to valid values for your machine. The current script is set for a possible 25 duplicates for any single file name. Change as necessary.

Good luck.


Discussion

No Comment Found