Copying and renaming files with same name

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Posts: 1
Joined: 17 May 2019 11:19

Copying and renaming files with same name

#1 Post by Tavz » 17 May 2019 11:24

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! =)

Posts: 3869
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Copying and renaming files with same name

#2 Post by aGerman » 18 May 2019 18:45

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

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

Post Reply