Windows: copy the file until the file exists

I want to use a Windows batch file to copy a file (myfile0001.bdg) from one specific directory to another. But I want to check if the file exists in the destination directory, and if the answer is yes, increase the file to 0001 and check again if the file exists (myfile0002.bdg), etc. While the file does not exist, and copy the file with a new name.

So, if in the destination 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 run the package, the new file will be myfile0008.bdg, etc.

I know that there is an IF EXIST command, but I don’t know what to do, what I need.

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

  • I'm on Windows 7 x32
  • : "C:\USERS\RAMBYTES\DOCUMENTS \"
  • : "P:\BACKUP \"
  • "MYFILE0001.BDG"
+5
3

- :

@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

, 1000 . , "" ""

: fooobar.com/questions/346365/...

+1
@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%

, .

+1
  • .

  • .

  • , .

  • ,

    4.1) ;

    4.2), , 3;

    4.3) .

  • , .

4.2 , , script , , . , .

script :

@ECHO OFF
SET "fname=%~n1"
SET counter=1%fname:~-4%
:loop
IF %counter% GTR 19999 (
  1>&2 ECHO Cannot copy the file: no free slots.
  EXIT /B 1
)
SET "targetname=%~2\%fname:~0,-4%%counter:~1%%~x1"
IF EXIST "%targetname%" (
  SET /A counter+=1
  GOTO loop
) ELSE (
  COPY %1 "%targetname%"
)

:

  • (~) - .

    script . , n x. , ( ), .

    FOR (

  • fname, . %fname:~-4, , fname. , : , 4- , , -4 , .

    , %fname:~0,-4%, : fname, . : , ( 0), 4 .

    %counter:~1 , (, 1) ( ).

    SET /?, .

  • counter . 1, , , .

    , , 0, CMD , 1 , . 1, %counter:~1.

0
source

All Articles