Batch to move files outside of randomly-named subfolders

266 Views Asked by At

I have a data set consisting of files organised according to the following hierarchical folder/subfolder structure:

enter image description here

I would like to remove all nuisance subfolders (move its contents outside of it at the same hierarchical level + delete the nuisance folder), thus ending up with the files organised like this: enter image description here

How can I achieve this, using a batch file, run from a command prompt inside Windows 7? I've tried a number of for statements with %F and %%F, but none worked. Grateful for any tips.

1

There are 1 best solutions below

4
On BEST ANSWER

I believe the following will accomplish your goal if and only if all child folder and file names are unique. If there are duplicates, then all hell will break loose.

I have not tested, so backup and/or try the code on disposable data first.

You will have to modify the first PUSHD command to point to the root where all your "person n" folders reside.

@echo off
pushd "yourRootWherePersonFoldersReside"
for /d %%U in (*) do (
  pushd "%%U"
  for /f "eol=: delims=" %%A in ('dir /b /ad 2^>nul') do (
    for /d %%B in ("%%A\*") do (
      for /d %%C in ("%%B\*") do (
        md "%%~nxC"
        for /d %%D in ("%%C\*") do move "%%D\*" "%%~nxC" >nul 2>nul
      )
    )
    rd /s /q "%%A"
  )
  popd
)
popd

The second FOR loop must be FOR /F instead of FOR /D because FOR /D has the potential to iterate folders that have been added after the loop has begun. FOR /F will cache the entire result of the DIR command before iteration begins, so the newly created folders are guaranteed not to interfere.