zcalebz
zcalebz

Reputation: 177

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

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.

Upvotes: 0

Views: 2661

Answers (1)

Endoro
Endoro

Reputation: 37569

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

Upvotes: 3

Related Questions