Batch file to recursively move files to first leve

2019-09-06 09:54发布

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条回答
一纸荒年 Trace。
2楼-- · 2019-09-06 10:53

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
查看更多
登录 后发表回答