Friday, April 6, 2018

windows - How to convert a tree directory into a single level directory


This question might be confused , it's better to show some example.
I have a folder that contain many sub-directory which might be multiple level.The structure below show the folder , all folder do contain their own file.


mainFolder
|--a
|--|--ab
|--|--ac
|--|--ad
|--b
|--b
|--|-cd
|--d

The above is the tree structure of mainFolder. I am trying to write a batch file that able to convert the whole tree into a single level structure.


--a
--ab
--ad
--b
--c
--cd
--d

Above is the expected output. All file should be in their own folder.


setlocal EnableDelayedExpansion
set "targetPath=%~dp0mainFolder"
for /r "%targetPath%" %%i in (.) do (
echo %%i
)
pause

This is my current code , which able to loop through and display the absolute path of the directory


Answer



There are inconsistencies: in source --c is missing in dest there is no --ac


Source tree:


> tree
└───mainFolder
├───a
│ ├───ab
│ ├───ac
│ └───ad
├───b
├───c
│ └───cd
└───d

Provided mainfolder is in the root of the drive this single cmdline:


@for /r "\mainfolder" %A in (.) do @for /f "tokens=5 delims=\" %B in ("%A") do @move "%A" "\mainFolder"

Will produce this destination tree:


> tree
└───mainFolder
├───a
├───ab
├───ac
├───ad
├───b
├───c
├───cd
└───d

If not adjust the tokens value from 5 to match the dirlevel.
In a batch file double all the percent signs %%


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...