How to Move Files/Folders Up the Directory Tree Using the Command Line

To solve this problem, utilize the provided batch file by substituting the root directory path. To gain a comprehension of the commands used and their functionality, open a command prompt window, execute the following commands, and thoroughly read the help pages displayed for each command. Use the “Append” command to suppress error messages, such as when the directory already exists. The MOVE commands are solely implemented for testing purposes.


Solution:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION 
SET "sourcedir=U:sourcedirt 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

To adapt to your specific situation, the setting of

sourcedir

may require modification.

Exercise caution when conducting the test by initially selecting a representative subtree.

For testing purposes, the necessary MD commands are only

ECHO

. Once you have confirmed the accuracy of the commands, replace

ECHO(MD

with

MD

to effectively create the directories. Add

2>nul

to
suppress error messages
when the directory already exists.

The MOVE commands specified as

ECHO

are only used for testing purposes. Once you have confirmed the accuracy of these commands, replace

ECHO(MOVE

with

MOVE

to initiate the actual file movement. Additionally, add

>nul

to suppress report messages, such as

1 file moved

.

The code section labeled

:loop

is responsible for removing any empty directories within the subtree. It is important to note that these commands are executed, rather than simply being displayed.

Exercise caution when using symbols with special meaning to

cmd

in file/directory names.

Frequently Asked Questions