Hutch
Hutch

Reputation: 501

Batch file copying from multiple directories with same file names

I am copying .gml files from one directory using a batch file.

My issue is that they are all in subdirectories and all called the same name.

What I have so far is:

FOR /r C:\Users\%USERNAME%\Downloads %%f in (*.gml) do copy %%~f C:\Users\%USERNAME%\Desktop\Inspire_Index_polygons\

This copies the files but overwrites the existing one, so I can see the batch file working because of the size of the file changes as it is overwritten each time.

Is there a way where I can copy the .gml files and rename the copied file with a recurring +1 so the name is always different when copied.

Upvotes: 1

Views: 1517

Answers (1)

user7818749
user7818749

Reputation:

Here is something that will help you achieve that. We test if the file exists in the destination, if it does, rename it appending (+1).

@echo off
setlocal enabledelayedexpansion
set "source=C:\Users\%USERNAME%\Downloads\"
set "dest=C:\Users\%USERNAME%\Desktop\Inspire_Index_polygons\"
set /a cnt=0
for /f "tokens=*" %%a in ('dir /S /B /A-D "%source%*.gml"') do for /f "tokens=*" %%b in ('dir /B "%%a"') do if exist "%dest%\%%b" (
        set "ext=%%~xa"
        set "fname=%%~na"
        if exist "%dest%\!fname!(!cnt!)!ext!" (set /a cnt=!cnt!+1)
        set /a cnt=!cnt!+1
        move "%%a" "%dest%\!fname!(!cnt!)!ext!"
) else move "%%a" "%dest%\%%b"

Upvotes: 1

Related Questions