Batch file to recursively move files to first level directory from deeper subdirectories

六月ゝ 毕业季﹏ 提交于 2019-12-13 04:37:40

问题


I have a hard drive with files and folders ordered in this similar manner:

F:\folder1\folder\folder\file.rar

F:\folder1\folder\folder\file1.rar

F:\folder1\folder\folder\file2.rar

F:\folder2\folder\file.rar

F:\folder2\folder\file1.rar

F:\folder3\folder\file.rar

F:\folder3\folder\folder\folder\file.rar

I'd like to move all files in this drive to F:\\*\ , Rename if a duplicate filename is found, and recursively delete empty folders afterwards. There's just too many of these folders to find out how deep each parent directory is. After executing the batch script the folders should look like:

F:\folder1\file.rar

F:\folder1\file1.rar

F:\folder1\file2.rar

F:\folder2\file.rar

F:\folder2\file1.rar

F:\folder3\file.rar

F:\folder3\file (1).rar

There might be folders with files already inside the F:\\*\ level. I want them to stay where they are.


回答1:


try this:

@ECHO OFF &SETLOCAL
FOR /r "F:\" %%a IN (*.rar) DO (
    SET "fname=%%~nxa"
    SET "fpath=%%~fa"
    FOR /f "tokens=1,2 delims=\" %%b IN ("%%~fa") DO SET "targetfolder=%%~b\%%~c"
    SETLOCAL ENABLEDELAYEDEXPANSION
    CALL :moveit "!fpath!" "!targetfolder!" "!fname!"
    ENDLOCAL
)
GOTO :eof

:moveit
SETLOCAL
SET "nname=%~3"
:loop
SET /a fcount+=1
IF EXIST "%~2\%nname%" (
    SET "nname=%~n3 (%fcount%)%~x3"
    GOTO :loop
)
ECHO MOVE "%~1" "%~2\%nname%"
MOVE "%~1" "%~2\%nname%"
ENDLOCAL
EXIT /b


来源:https://stackoverflow.com/questions/18295056/batch-file-to-recursively-move-files-to-first-level-directory-from-deeper-subdir

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