Page 1 of 1

Copying and renaming files with same name

Posted: 17 May 2019 11:24
by Tavz
Hello guys! I recently made a script that copies every single file from a folder - no matter if it's inside another folder in this folder - to another folder of my choice, so I can see all the files in a single place. Here it is:

For /r "c:\source" %d in (*) do copy "%d" "E:\destiny"

The problem is, there are some files with the same name, I mean: c:/source/folder1/FileName.pdf has the same name as c:/source/FileName.pdf

And I would like to, instead of substitute it or not, rename it to FileName1 - also, if there are 3 files, make it rename the third one to FileName2 and so on

Is it easy to do that? I'm new to scripts and I feel like I need to use a "for". Can someone give me a hand?

Sorry for bad english! =)

Re: Copying and renaming files with same name

Posted: 18 May 2019 18:45
by aGerman
In a batch script you could do it like that:

Code: Select all

@echo off &setlocal
set "src=C:\source"
set "dst=D:\destination"

for /r "%src%" %%i in (*) do (
  if not exist "%dst%\%%~nxi" (
    copy "%%~i" "%dst%\"
  ) else (
    set "fullname=%%~i"
    set "name=%%~ni"
    set "ext=%%~xi"
    set "idx=0"
    call :newname
  )
)
exit /b

:newname
set /a "idx+=1"
if exist "%dst%\%name%%idx%%ext%" goto newname
copy "%fullname%" "%dst%\%name%%idx%%ext%"
exit /b
Steffen