如何使用批处理文件复制(和递增)文件的多个实例

问题描述 投票:4回答:2

我需要创建一个批处理文件,该文件将复制文件并在将其放置到目标位置时对其进行递增。范例。

copy C:\TEMP\MyDoc.txt E:\MyData\

基本上,每次启动时,我都需要此复制命令来复制它(现在就可以了)。我希望它增加文件名而不是覆盖它。如果我运行了3次或100次(从来没有确定的次数),我希望在“ MyData”文件夹中看到:

MyDoc.txt

MyDoc(1).txt

...

或复制(1)我不太确定复制文件的语法是什么,我也不必关心。我只想确保我不会覆盖跳转驱动器上的现有文件。

不足之处是,我正在运行Windows CE的旧Allen Bradley PanelView Plus上执行此操作。任何帮助将不胜感激。

batch-file copy backup windows-ce increment
2个回答
4
投票

您可以尝试这样:

@echo off
set Source=C:\TEMP\MyDoc.txt
set Destination=E:\MyData\
set Filename=MyDoc
set a=1

:loop
if exist %Destination%\%Filename%(%a%).txt set /a a+=1 && goto :loop
copy %Source% %Destination%\%Filename%(%a%).txt
pause

0
投票

以下是一些打屁股的代码:

放入一个名为easycopy.bat的文件,并使用like,“ easycopy SourceDirectory DestinationDirectory”。

@rem easycopy
@rem Usage: easycopy SourcePath TargetPath (SourcePath can be the path to a directory or a single file)
@rem release 24/05/2020
@echo off

setlocal enableDelayedExpansion

rem Initialize and validate arguments
if "%~2" equ "" echo Error: Insufficient arguments>&2&exit /b 1
set "source=%1"
set "target=%2"
set /a counter=0
if not exist %target%\ echo Error: Target folder %target% does not exist>&2&exit /b 1

if not exist %source%\ call :newfile %source% %target% & set /a counter+=1 & goto :end

rem Do the work
for /r %source% %%F in (*) do if "%%~dpF" neq %target%\ (
  if exist %target%\"%%~nxF" (
    call :newfile "%%F" %target% & set /a counter+=1
  ) else copy "%%F" %target% >nul & set /a counter+=1
)

:end
echo.
if %errorlevel% EQU 0 echo %counter% file/s was/were copied.
if %errorlevel% GTR 0 echo Check if something went wrong.
goto :eof

:newfile <Source> <Destination>
set Source=%1
set Destination=%2
set Filename=%~n1
set Extention=%~x1
set a=1
:loop
if not exist %Destination%\"%Filename%%Extention%" copy %Source% %Destination%\"%Filename%%Extention%" >nul & goto :eof
if exist %Destination%\"%Filename%(%a%)%Extention%" set /a a+=1 && goto :loop
copy %Source% %Destination%\"%Filename%(%a%)%Extention%" >nul
© www.soinside.com 2019 - 2024. All rights reserved.