A script package that moves each file in a folder to its own folders named after the file?

So, if I have

/folder/file1.txt /folder/file2.jpg /folder/file3.py 

I want to create

 /folder/file1/file1.txt /folder/file2/file2.jpg /folder/file3/file3.py 

I have this batch file (be careful when you run it) that basically works, but if there are spaces in the file name, the folder name will only be named before the space, and therefore the file will not be moved inside it.

Also, I only got it to work by randomly typing the word "Folder" or some random string at the end of the folder name, if I exclude this, for some reason this will not work. I'm on windows 7.

 @echo off for /f %%a in ('dir /ad /b') do ( if not "%%~dpnxa"=="%~dpnx0" call :func "%%~a" ) goto :EOF :func set file=%~1 set dir=%file% Folder md "%dir%" Folder 2>nul move "%file%" "%dir%" goto :EOF 

Any ideas for solving problems with spaces / names? Thanks in advance.

+2
file folder batch-file
source share
2 answers
 @echo off for /f "usebackq delims=?" %%a in (`dir /ad /b`) do ( if not "%%~dpnxa"=="%~dpnx0" call :func "%%~a" ) goto :EOF :func set file=%~1 set dir=%file% Folder md "%dir%" Folder 2>nul move "%file%" "%dir%" goto :EOF 

By setting delims =? Are you saying your separator? to separate a line, instead of a space character, which allows you to read full file names with spaces in them. Usebackq means that instead you use `around the command to run, which for me just makes it more logical to read and understand" Hey, I really execute this line. "

+2
source share

To avoid problems with spaces in the path / file names, specify all links to them twice.

The reason for including a line at the end of the folder in your code is an attempt to create a folder with the same name as the file (in the code, you do not delete the extension), and you cannot have two elements (files or folders) inside the folder with the same name.

 @echo off for %%a in ("c:\folder\*") do ( if not "%%~fa"=="%~f0" ( if not exist "%%~dpna\" echo md "%%~dpna" if exist "%%~dpna\" echo move /y "%%~fa" "%%~dpna" ) ) 

For each file in the specified folder

  • if the file is not a batch file

    • if the folder with the same name as the file does not exist, create it
    • if the destination folder exists, move the file to the folder

%%~fa = full path of the file being processed

%~f0 = full path to the batch file

%%~dpna = disk name, path and file name without the extension of the current file that is running

In this code, the reason for the third if is to check if the possible creation of the previous folder failed. If you have a file without an extension, you cannot create a folder, since it will have the same name as the file, and this is not allowed.

There are echo commands in the code before md and move to indicate that it will be executed. If the output is correct, delete echo to make it work.

+1
source share

All Articles