Link to home
Start Free TrialLog in
Avatar of weklica
weklica

asked on

recursive copy needs to rename existing files.

The code below works great for recursive copying of files.  What do I do though, if the same file name exists in the source\*\ subdirectories?  currently, if a file name is 1, and it exists twice, the last number 1 is the only file remaining.  I would like to make sure this doesn't happen.  Can I append the folder tree as part of the file name or just have sequential numbering of 001 , 002 , etc. append to the first file whose name is the same of a new file trying to copy or something along these lines?  I know xxcopy /sx will do it, but i am trying to get away from that.  Thanks
for /f "tokens=*" %%a in ('dir /a-d /b /s "c:\source"') do copy "%%a" "c:\destination

Open in new window

Avatar of Shift-3
Shift-3
Flag of United States of America image

I'm not sure if this is exactly what you're after, but here is a batch script I wrote a while ago which includes the previous path in each file's name.


@echo off
setlocal enabledelayedexpansion
 
set source=c:\source
set mask=*.*
set dest=c:\destination
 
for /F "tokens=*" %%G in ('dir "%source%\%mask%" /A:-D /B /S 2^> NUL') do (
 set newname=%%G
 set newname=!newname:~3!
 set newname=!newname:\=.!
 echo F | xcopy "%%G" "%dest%\!newname!" /C /H /R /Y > NUL
)

Open in new window

You are quite right to be concerned about duplicate filenames when copying from different sources to a single destination.

There are a number of ways this can be solved including generating a fixed or variable length random number prefix or postfix to the filename. In some cases it is possbile to prefix or postfix the date or time but this is not foolproof. My favorite approach is to postfix the filename with a 3-digit sequential number. The reason for this is it lists the files in order of creation during a DIR command.

Here's an example:

    Letter_to_john.doc
    Letter_to_john-001.doc
    Letter_to_john-002.doc
    etc...

Please copy the code into Notepad and save as CPYALL21.BAT and run the batch file by typing:

    CPYALL21

on a DOS command line.


@rem CPYALL21.BAT
@echo off
set source=c:\source
set destination=c:\destination
setlocal enabledelayedexpansion

for /f "tokens=*" %%a in ('dir /a-d /b /s "%source%"') do (
   set filename=%%~nxa
   if exist "%destination%\!filename!" call :GetNewFN "!filename!"
   copy "%%a" "%destination%\!filename!">nul
)
exit /b

:GetNewFN
set count=0
:loop
   set /a count+=1
   set count=100%count%
   set count=%count:~-3%
   set filename=%~n1-%count%%~x1
if exist "%destination%\%filename%" goto loop
exit /b
ASKER CERTIFIED SOLUTION
Avatar of t0t0
t0t0
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of weklica
weklica

ASKER

Sorry for delay on response!
thank you