如果文件存在,请将文件另存为 [英] Copy file as another name if file exist

查看:192
本文介绍了如果文件存在,请将文件另存为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要将特定文件从pc复制到usb

I want to copy specific file from pc to usb

我的代码:

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

我想做以下操作:
如果存在G:\backup\image1.jpeg,将image.jpeg复制为image2.jpeg(或作为另一个名称),

i want to do following : if G:\backup\image1.jpeg exist, copy image.jpeg as image2.jpeg (or as another name),

如果image2.jpeg存在,请复制为image3.jpeg和ect ..

if image2.jpeg exist, copy as image3.jpeg and ect..

这样做?

推荐答案

我假设你的源名是image.jpeg

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.

这是一个粗略但非常有效的强力方法,最多支持100个副本。显然上限很容易增加。

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
)

但是有一个潜在的问题。假设image.1.txt和image.2.txt已经存在,但是您删除了image.1.txt。下次备份时,它将重新创建image.1.txt,然后您可能认为image.2.txt是最新的备份。

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.

以下可以用于始终创建一个新的备份,其后缀1大于最大的现有后缀,即使数字中有整数。

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

这篇关于如果文件存在,请将文件另存为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆