Windows CMD – How to Move All Files from Subfolders to Parent Folder

batch filecmd.exewindows

I would normally open the parent folder and search for * in order to select all of the files in subfolders, but in this instance, I have over 1,000,000 files that I need to sort through, so my explorer often crashes when trying to copy that many files through the GUI. I am not sure how much more effective this will be through the command prompt or a batch file, but it is worth a try, I suppose.

What I need to do is make it so that

|parent
|    |123
|    |    123abc.png
|    |456
|    |    456def.png
|    |789
|    |    789ghi.png

becomes

|parent
|    123abc.png
|    456def.png
|    789ghi.png

Yes, my actual file structure has the first 3 characters of the file name given to the folder name, if that can help at all in sorting these.

Best Answer

Use FOR /R at the command prompt:

[FOR /R] walks down the folder tree starting at [drive:]path, and executes the DO statement against each matching file.

First create a staging folder outside of the parent folder you're moving files from. This will avoid possible circular references.

In your case the command would look something like this:

FOR /R "C:\Source Folder" %i IN (*.png) DO MOVE "%i" "C:\Staging Folder"

If you want to put this into a batch file, change %i to %%i.

Note the double-quotes are important, don't miss any of them out. They ensure any filenames containing spaces are dealt with correctly.

Once the move is complete, you can rename/move the staging folder as required.

TIP: If you have hard drive space to burn and time on hand, you may want to play it safe and copy the files rather than moving them, just in case something goes wrong. Just change MOVE to COPY in the above command.

Related Question