Reputation: 2733
I have a folder containing a bunch of subfolders and files, but the structure is a bit inefficient. For example:
Root Folder
----EmptyFolder1
--------Folder1
------------SubFolder1
------------File1
------------File2
----EmptyFolder2
--------Folder2
------------SubFolder2
------------File3
------------File4
How can I move all of the Folders/SubFolders/Files up in the tree and eliminate all of the EmptyFolders so that it looks more like this:
Root Folder
----Folder1
--------SubFolder1
--------File1
--------File2
----Folder2
--------SubFolder2
--------File3
--------File4
Upvotes: 0
Views: 1266
Reputation: 79983
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir\t h r e e"
FOR /f "delims=" %%a IN (
'dir/s/b/a-d "%sourcedir%"'
) DO (
CALL :movefile %%a
)
:loop
SET "zapped="
FOR /d /r "%sourcedir%" %%a IN (.) DO (
RD "%%a" >NUL 2>NUL
IF NOT EXIST "%%a" SET zapped=Y
)
IF DEFINED zapped GOTO loop
DIR /s/b/ad "%sourcedir%
GOTO :EOF
:movefile
SET "oldfn=%*"
SET "newfn=!oldfn:%sourcedir%\=!"
SET "newfn=%sourcedir%\%newfn:*\=%"
FOR %%r IN ("%newfn%") DO (
ECHO MD "%%~dpr"
ECHO MOVE "%oldfn%" "%newfn%"
)
GOTO :eof
You would need to change the setting of sourcedir
to suit your circumstances.
caution test on a representative subtree first!
The required MD commands are merely ECHO
ed for testing purposes. After you've verified that the commands are correct, change ECHO(MD
to MD
to actually create the directories. Append 2>nul
to suppress error messages (eg. when the directory already exists)
The required MOVE commands are merely ECHO
ed for testing purposes. After you've verified that the commands are correct, change ECHO(MOVE
to MOVE
to actually move the files. Append >nul
to suppress report messages (eg. 1 file moved
)
The section after the :loop
label deletes any empty directories in the subtree. Of necessity, the commands are executed not merely displayed.
Be very, very careful about file/directorynames that contain symbols with special meaning to cmd
.
Upvotes: 1