我正在编写一个脚本,用于复制与文件名相对应的文件夹中的文件,并且我使用FOR循环来完成该部分,该循环检查以确保目标文件夹存在并在验证后复制文件它确实如此。示例:11-01111_ABC_DEF.pdf将进入/ 11/0111 /。长度可能会有一个或两个字符,但格式是一致的。我在下面复制了我的基本脚本。
我的问题是,有时需要处理具有相同名称的文件。如果目标文件夹中已存在该文件的一个或多个副本,我怎么能将数字连接到文件的末尾?
setlocal enableextensions enabledelayedexpansion
for %%x in (*.PDF *.TXT) do (
set "source="C:\files"
set "dest=R:\"
set "filename=%%x"
set "prefix=!filename:~0,2!"
set "folder=!filename:~3,5!"
if not exist !dest!\!prefix!\!folder! MOVE !filename! !source!\failed
if exist !source!\!filename! MOVE !filename! !dest!\!prefix!\!folder!
)
答案 0 :(得分:0)
setlocal ENABLEDELAYEDEXPANSION
set "dest=worked"
for %%i in (*.pdf *.txt) do (
for /f "tokens=1-3* delims=-_." %%j in ("%%i") do (
if exist "%dest%\%%j\%%k" if exist "%dest%\%%j\%%k\%%i" if exist "%dest%\%%j\%%k\%%j-%%k-1_%%l_%%m" (
for /f "tokens=1-9* delims=-_." %%n in ('dir %dest%\%%j\%%k\%%j-%%k*-* /b') do set /a inc=%%p
set /a inc+=1
move "%%i" "%dest%\%%j\%%k\%%j-%%k-!inc!_%%l_%%m" || move "%%~i" "failed"
set inc=
)
if exist "%dest%\%%j\%%k\%%i" if not exist "%dest%\%%j\%%k\%%j-%%k-1_%%l_%%m" (
move "%%i" "%dest%\%%j\%%k\%%j-%%k-1_%%l_%%m" || move "%%~i" "failed"
)
if exist "%dest%\%%j\%%k" if not exist "%dest%\%%j\%%k\%%~i" (
move "%%~i" "%dest%\%%j\%%k\%%~i" || move "%%~i" "failed"
)
if not exist "%dest%\%%j\%%k" move "%%~i" "failed"
)
)
如果你想让我改变一些东西,请把它放在带有.texts和.pdfs注释的文件夹中。
答案 1 :(得分:-1)
setlocal EnableDelayedExpansion
rem Set the maximum number of repeated names (keep it low):
set maxNumber=9
set "source=C:\files"
set "dest=R:\"
for %%x in (*.PDF *.TXT) do (
for /F "tokens=1,2 delims=-_" %%a in ("%%x") do (
set "prefix=%%a"
set "folder=%%b"
)
set "filename=%%x"
if not exist %dest%\!prefix!\!folder! MOVE !filename! %source%\failed
if exist %source%\!filename! (
set "destname=!filename!"
rem If destination filename already exists: concatenate a sequential number
if exist %dest%\!prefix!\!folder!\!destname! (
set "filename=%%~Nx"
set "destname="
for /L %%i in (1,1,%maxNumber%) do if not defined destname (
if not exist %dest%\!prefix!\!folder!\!filename!-%%i%%~Xx set destname=!filename!-%%i%%~Xx
)
)
MOVE !filename! %dest%\!prefix!\!folder!\!destname!
)
)