Copy file as another name if file exist

前端 未结 1 1709
既然无缘
既然无缘 2021-01-27 22:52

I want to copy specific file from pc to usb

my code :

  xcopy /H /Y /C /R \"C:\\image1.jpeg\" \"G:\\backup\\image.jpeg\"

i want to do

相关标签:
1条回答
  • I'm going to assume your source name is "image.jpeg" and your destination has the appended suffix.

    I recommend putting a dot before the appended suffix to make it clear where the original name ends and the suffix begins. Your original name could already have a number at the end.

    Here is a crude but very effective brute force method that supports up to 100 copies. Obviously the upper limit can easily be increased.

    call :backup "c:\image.jpeg"
    exit /b
    
    :backup
    for /l %%N in (1 1 100) do (
      if not exist "G:\backup\%~n1.%%N.%~x1" (
        echo F|xcopy %1 "G:\backup\%~n1.%%N.%~x1" >nul
      )
      exit /b
    )
    

    But there is a potential problem. Suppose image.1.txt and image.2.txt already exist, but then you delete image.1.txt. The next time you backup it will re-create image.1.txt and then you might think that image.2.txt is the most recent backup.

    The following can be used to always create a new backup with the number suffix 1 greater than the largest existing suffix, even if there are wholes in the numbers.

    @echo off
    call :backup "c:\image.jpeg"
    exit /b
    
    :backup
    setlocal disableDelayedExpansion
    set /a n=0
    for /f "eol=: delims=" %%A in (
      'dir /b "g:\backup\%~n1.*%~x1"^|findstr /rec:"\.[0-9][0-9]*\%~x1"'
    ) do for %%B in ("%%~nA") do (
      setlocal enableDelayedExpansion
      set "n2=%%~xB"
      set "n2=!n2:~1!"
        if !n2! gtr !n! (
        for %%N in (!n2!) do (
          endlocal
          set "n=%%N"
        )
      ) else endlocal
    )
    set /a n+=1
    echo F|xcopy %1 "g:\backup\%~n1.%n%%~x1" >nul
    
    0 讨论(0)
提交回复
热议问题