Copy file as another name if file exist

我是研究僧i 提交于 2019-12-02 07:48:38

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!