CMD Command to create folder for each file and move file into folder

I need a command that can be run from the command line to create a folder for each file (based on the file-name) in a directory and then move the file into the newly created folders.

Example :

Starting Folder:

Dog.jpg
Cat.jpg

The following command works great at creating a folder for each filename in the current working directory.

for %i in (*) do md "%~ni"

Result Folder:

\Dog\
\Cat\
Dog.jpg
Cat.jpg

I need to take this one step further and move the file into the folder.

What I want to achieve is:

\Dog\Dog.jpg
\Cat\Cat.jpg

Can someone help me with one command to do all of this?

0

3 Answers

The second command would be

for %i in (*) do move "%i" "%~ni"

EDIT: Added "" for the %i, based on and31415's comment. tnx.

3

Just execute these commands in series:

For creating the folders for each file:

for %i in (*) do mkdir "%~ni"

For moving each file to its folder:

for %i in (*) do move "%i" "%~ni"
2

This will do it if you have some folders like: example years\Filename.mp4

1901\Filename.mp4
1902\Filename.mp4
1903\Filename.mp4

it will list all the folder 1st level files; lists all *.mp4 and *.mkv will create the 2 level folders with the filename and will move all the same name files in the 1st level folder to the 2nd level folder, run it at the years base folder.

for /d %D in (*) do for %i in (%~fD\*.mp4,%~fD\*.mkv) do mkdir "%~dpi%~ni" && move "%~dpi%~ni.*" "%~dpi%~ni\"

If you don't have a 1st level YEARS folder you can just bypass the first for and run the 2nd step, run it at the filename base folder.

for %i in (*.mp4,*.mkv) do mkdir "%~dpi%~ni" && move "%~dpi%~ni.*" "%~dpi%~ni\"

The && will ensure that the previous mkdir %ERRORLEVEL% is 0 to run the move of the files

To test, use this:

for /d %D in (*) do for %i in (%~fD\*.mp4,%~fD\*.mkv) do echo "%~dpi%~ni" && echo "%~dpi%~ni.*" "%~dpi%~ni\"
2

You Might Also Like