Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows: copy a file until the file not exist

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.

==============

  • I'm under Windows 7 x32
  • The source directory is "C:\USERS\RAMBYTES\DOCUMENTS\"
  • The target directory is "P:\BACKUP\"
  • The file is "MYFILE0001.BDG"
like image 550
user2129046 Avatar asked Nov 04 '22 03:11

user2129046


2 Answers

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

like image 119
a_horse_with_no_name Avatar answered Nov 10 '22 20:11

a_horse_with_no_name


@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.

like image 20
Magoo Avatar answered Nov 10 '22 21:11

Magoo