I want to use a Windows batch file in to copy a file (myfile0001.bdg) from one specific directory to another. But I want to check if the file in the target directory exists and if the answer is yes, increment the file with 0001 and check again if the file exists (myfile0002.bdg) and so on, until the file does not exist, and copy the file with the new title.
So, if in the target directory, I have these files:
myfile0001.bdg myfile0002.bdg myfile0003.bdg myfile0004.bdg myfile0005.bdg myfile0006.bdg
The new file should be named myfile0007.bdg. The next time I will execute the batch, the new file will be myfile0008.bdg, etc.
I know there is a command "IF EXIST" but I don't know to do what I need.
==============
Something like this:
@echo off
set source_file=C:\USERS\RAMBYTES\DOCUMENTS\MYFILE0001.BDG
set target_dir=P:\BACKUP\
set done=0
for /l %%i in (1,1,1000) do (
call :check_and_copy %%i
if errorlevel 1 goto :eof
)
goto :eof
:check_and_copy
setlocal EnableDelayedExpansion
set num=000000%1
set fnum=!num:~-4!
set fname=%target_dir%\myfile%fnum%.bdg
rem echo %fname%
if not exist "%fname%" (
echo copying %source_file% to %fname%
exit /b 1
)
exit /b 0
There is no error handling in case there are more than a 1000 files present in the target directory. If you want to increas the file limit, you need to adjust the "main" for loop and the "formatting" of the number in the sub-program
The trick with adding the leading zeros was taken from here: https://stackoverflow.com/a/9430912/330315
@ECHO OFF
SET destdir=c:\destdir
SET newname=myfile0000
FOR /f %%i IN (' dir /b /on %destdir%\myfile????.bdg ' ) DO SET newname=%%~ni
SET newname=1%newname:~-4%
SET /a newname+=1
SET newname=myfile%newname:~-4%.bdg
COPY myfile0001.bdg %destdir%\%newname%
change the destination directory as desired, and include the source directory if required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With