我有以下代码来搜索多个文件夹中的特定文件名(ratings.zil)并将其复制到新文件夹中:
for /R %f in (ratings.zil) do @IF EXIST %f copy "%f" "C:\here"
但是,当文件复制到新文件夹时,它将覆盖而不是在每个ratings.zil
的末尾附加一个数字,即ratings(1).zil
,ratings(2).zil
。有没有一种方法可以在上述代码中添加一个循环,该循环将在每个文件后附加一个数字?
该问题最初被标记为重复问题,但重复问题的答案仅在您在同一文件夹中复制文件时才有效。
答案 0 :(得分:0)
这里是DBenhams answer的略微修改版本。
@echo off
setlocal disableDelayedExpansion
if "%~2" equ "" echo Error: Insufficient arguments>&2&exit /b 1
set "source=%~f1"
set "target=%~f2"
md "%target%"
set /a cnt=0
for /r "%source%" %%F in (ratings.zil) do if "%%~dpF" neq "%target%\" (
if exist "%%F" (
if exist "%target%\%%~nxF" (
set /a cnt+=1
set "full=%%F"
set "name=%%~nF"
set "ext=%%~xF"
setlocal enableDelayedExpansion
copy "!full!" "!target!\!name!(!cnt!)!ext!" >nul
endlocal
) else copy "%%F" "%target%" >nul
)
)
要运行此程序,您需要将文件另存为myRename.cmd
,然后只需打开cmd.exe并运行为:
myRename.cmd "C:\Source of files" "D:\Destination"
如果您希望将此文件放置在设置的目录中并且具有静态目标文件夹,并且能够双击它,则可以这样做:
@echo off
setlocal disableDelayedExpansion
set "target=C:\here"
md "%target%"
set /a cnt=0
for /r %%F in (ratings.zil) do if "%%~dpF" neq "%target%\" (
if exist "%%F" (
if exist "%target%\%%~nxF" (
set /a cnt+=1
set "full=%%F"
set "name=%%~nF"
set "ext=%%~xF"
setlocal enableDelayedExpansion
copy "!full!" "!target!\!name!(!cnt!)!ext!" >nul
endlocal
) else copy "%%F" "%target%" >nul
)
)