我有一个包含文件的文件夹和一个.txt文件,其中包含文件名列表和从一个文件夹复制到另一个文件夹所需的拷贝数。
脚本正在复制文件,但是如果.txt文件有两个同名的文件,它将覆盖旧文件。
在我的名单中:
文件1.txt 1 file2.txt 1 file1.txt 3 file2.txt 2
我要做到以下几点:
.txt file1(1).txt file1(2).txt file1(3).txt file2(1).txt
这是我到目前为止掌握的代码:
@echo off
set Source=C:\Users\siddique.gaffar\Desktop\Artworks
set Target=C:\Users\siddique.gaffar\Desktop\Artworks Copy
set FileList=C:\Users\siddique.gaffar\Desktop\Artwork TXT File\Book1.txt
echo.
if not exist "%Source%" echo Source folder "%Source%" not found & goto Exit
if not exist "%FileList%" echo File list "%FileList%" not found & goto Exit
if not exist "%Target%" md "%Target%"
for /F "delims=" %%a in ('type "%FileList%"') do copy "%Source%\%%a" "%Target%"
:Exit
echo.
echo press the Space Bar to close this window.
pause > nul发布于 2017-01-29 01:00:58
以下是其中的诀窍:
@echo off
set Source=C:\Users\siddique.gaffar\Desktop\Artworks
set Target=C:\Users\siddique.gaffar\Desktop\Artworks Copy
set FileList=C:\Users\siddique.gaffar\Desktop\Artwork TXT File\Book1.txt
echo.
if not exist "%Source%" echo Source folder "%Source%" not found & goto Exit
if not exist "%FileList%" echo File list "%FileList%" not found & goto Exit
if not exist "%Target%" md "%Target%"
for /F "usebackq tokens=1-2" %%a in ("%FileList%") do call :CopyFile "%%a" %%b
:Exit
echo.
echo press the Space Bar to close this window.
pause > nul
exit /b 0
:CopyFile
:: first argument = filename
:: second argument = number of copies
REM A little trick that will put limit on 0 if second argument is empty or not a number
set secondarg=%~2
set /a limit=secondarg
REM if limit is invalid (not strict positive), exit the function
IF %limit% LEQ 0 (
echo Invalid number of copies
exit /b 1
)
IF NOT EXIST "%Target%\%~1" (
copy "%Source%\%~1" "%Target%"
IF %limit% LEQ 1 exit /b 0
set /a limit-=1
)
REM File already exists: search correct index for filename
set index=0
set "targetfile=%target%\%~n1"
set file_ext=%~x1
:following
set /a index+=1
Rem if file with index %index% already exists, go back to get following index
IF exist "%targetfile%(%index%).%file_ext%" goto :following
Rem we have the correct index, now we can copy
set /a limit=index+limit-1
FOR /L %%g IN (%index%,1,%limit%) DO copy "%Source%\%~1" "%targetfile%(%%g).%file_ext%"
exit /b 0如果您有长文件名,另一个选项是使用usebackq并在for f循环中使用双引号包围路径,而不是分析type命令的输出。
函数:CopyFile使用IF EXIST检查文件的存在,并使用计数器为新文件的文件名查找下一个索引。它使用路径操纵来使用索引构造一个新的文件名。
编辑:我增加了从文本文件中读取所需拷贝数的可能性,并将该数字指定为:CopyFile函数的第二个参数。如果没有给出数字,或者数字不是严格正数(大于0),它就不会复制。
PS:我使用的“小技巧”将%limit%设置为0,以防第二个参数为空,因为带有/a标志的set将用0替换空变量。但是,如果直接使用参数变量,这是行不通的:
set /a limit=%~2如果第二个参数为空,则会抛出一个错误,因为cmd解析器将用空字符串替换%~2,并使用/a标志执行set /a limit=,这是一个无效的分配。但是,如果您使用额外的变量作为传输:
set var=%~2
set /a limit=var您将让set处理变量展开,而不是cmd解释器。set将看到var变量为空(在这种情况下,%2为空),并将其替换为0。
https://stackoverflow.com/questions/41913799
复制相似问题