问题描述
我有以下代码来搜索多个文件夹中的特定文件名(ratings.zil),并将其复制到新文件夹中:
I have the following code to search for a specific file name (ratings.zil) across multiple folders and copy them to a new folder:
for /R %f in (ratings.zil) do @IF EXIST %f copy "%f" "C:\here"
但是,当文件复制到新文件夹时,它将覆盖而不是在每个ratings.zil
的末尾附加数字-即ratings(1).zil
,ratings(2).zil
.有没有一种方法可以在上述代码中添加一个循环,该循环将在每个文件后附加一个数字?
But when the file copies to the new folder it overwrites instead of appending a number at the end of each ratings.zil
– i.e. ratings(1).zil
, ratings(2).zil
. Is there a way to add a loop to the above code that will append a number after each file?
该问题最初被标记为重复问题,但重复问题的答案仅在您在同一文件夹中复制文件时才有效.
This question was originally marked as a duplicate, except the answer for the duplicate only works when you’re copying a file within the same folder.
推荐答案
以下是.
@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并以以下方式运行它即可:
In order to run this, you need to save the file as something like myRename.cmd
then simply open cmd.exe and run it as:
myRename.cmd "C:\Source of files" "D:\Destination"
如果您希望将此文件放置在设置的目录中并且具有静态目标文件夹,并且只需双击它,那么它将执行以下操作:
If you perfer to place this in a set directory and have a static destination folder and be able to just double click it, then this will do:
@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
)
)
这篇关于将相同文件名从不同文件夹复制到新文件夹时,追加文件名的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!