Loop that appends filename when copying same filename from different folders to a new folder

此生再无相见时 提交于 2020-01-06 07:24:11

问题


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"

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.


回答1:


Here is a slightly ammended version of 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
 )
)

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
 )
)


来源:https://stackoverflow.com/questions/53389425/loop-that-appends-filename-when-copying-same-filename-from-different-folders-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!