'Sorting Folders alphabetically using a batch file

I need to sort a large number of files folders from alphabetical blocks of four to each individual letter. I have been attempting to do this using a batch file but instead it appears to be copying every single file, no matter the first letter, to the folder for every single letter. I've tried a number of different methods and I have not found any success.

Here is the closest I have managed to get:

@echo off
@echo Started: %date% %time%
setlocal enabledelayedexpansion

cd "D:\The Files\A - D"
echo %time%: Processing Block A - D
for %%I in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
   echo %time%: Processing %%I
   xcopy "D:\The Files\A - D\%%I*" "D:\The Files\%%I" /E
)

@echo Finished: %date% %time%

I'm limited to using batch files by my network IT policy.



Solution 1:[1]

@ECHO OFF
SETLOCAL
echo Started: %date% %time%
SET "dirs="A - D" "F - I" "J - M" "N - R" "S - V" "W - Z""
pushd "U:\The Files"
FOR %%s IN (%dirs%) DO (
 echo %time%: Processing Block %%~s
 for %%I in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
   IF EXIST ".\%%~s\%%I*" (
    echo %time%: Processing %%I
    ECHO xcopy "D:\The Files\%%~s\%%I*" "D:\The Files\%%I\" /E
   )
 )
)
popd

@echo Finished: %date% %TIME%

You've only given us one block, so I've guessed the rest. Also, I use U: for testing and the xcopy has been disarmed by an echo so that you can see what the xcopy command would be if the echo keyword was removed from the line.

dirs is set to a list of subdirectory-names. Each name is quoted and then the entire set command argument is quoted; hence it ends with two quotes.

Use set "var1=value" for setting STRING values - this avoids problems caused by trailing spaces.

Then, the for %%s takes each name in turn and applies it to %%s (including the quotes). We can then use %%~s to remove thos enclosing quotes.

So - for each letter, see whether any (presumed, file) exists in the current block that starts with the letter. If so, show the time & letter being processed and do the XCOPY.

Solution 2:[2]

Seems you want to copy all the files based on the first character of the file. Considering the directories are actually A - D etc.

@echo off
setlocal enabledelayedexpansion
set "dest=D:\The Files"
for /D %%a in ("? - ?") do (
pushd "%%a"
for /F "delims=" %%i in ('dir /b') do (
    set "line=%%~i"
    echo "%%a" xcopy "!line:~0,1!*%%~xi" "%dest%\!line:~0,1!" /E
 )
 popd
)

remove echo from the line before the closing parenthesis, only if the displayed results are what you are after to perform the actual copy.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Magoo
Solution 2