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

4

我需要创建一个批处理文件,将一个文件复制并在放置到目的地后递增它。例如:

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

基本上,我需要这个复制命令每次启动时都能复制(现在它可以做到)。我希望它递增文件名而不是覆盖它。如果我运行三次或100次(从不确定的数字),我希望在“ MyData”文件夹中看到:

MyDoc.txt

MyDoc(1).txt

...

或复制(1),我不太确定重复文件的语法,也不一定关心。我只想确保我没有覆盖跳马盘上预先存在的文件。

问题在于我正在使用一个旧的Allen Bradley PanelView Plus并运行Windows CE。非常感谢任何帮助。


答案在此页面上:https://stackoverflow.com/questions/46397166/copy-file-to-destination-folder-and-keep-duplicates/61986897#61986897 - Toten Hosen
2个回答

5
你可以尝试这样做:
@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

我使用这段代码没有任何运气。我一直收到一个错误,说:“|:命令语法不正确” - Dustin11h3
1
更新:我在我的笔记本电脑上运行它,结果很好。但是当我在Windows CE机器上运行它时,出现了问题。感谢Hackoo的帮助。我已经使用了另一种方法来完成我需要做的事情。那段代码足够简单(因为我有一些编程背景),只是我不知道如何在批处理中实现。再次感谢。 - Dustin11h3

0
这是一些很棒的代码:
将其放入名为easycopy.bat的文件中,并使用如下方式: “easycopy 源目录 目标目录”。
@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

也可处理单个文件。 - Toten Hosen
“spanking code” 是什么意思? - Peter Mortensen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接