Search code examples
filebatch-filedirectorymove

Speed up Batch file processing, moving file to folder of same name


I need some help moving files into folders of the same name. I have a batch file that works but it is very slow. I'm moving approximately 3300 .xlsx files into folders with like names. Here is what I have thus far:

@echo off
setlocal EnableDelayedExpansion
pushd "C:\New folder"
FOR %%G IN (*.xlsx) DO (
FOR /F "tokens=1 delims= " %%a IN ("%%G") do (
set "outFolder=%%a "
for /D %%i in (*.*) do (
  for /F "tokens=1 delims= " %%b IN ("%%i") do (
    if "%%a"=="%%b" set "outFolder=%%i"
  )
 )
if not exist "!outfolder!" md "!outfolder!"
move "%%G" "!outfolder!"
)
)
popd
pause

Again this works but is slow. This code moves the files to folder and if folder doesn't exist it creates it.

I have found this code and it works to a point. The following code does not seem to recognize the folders that already exist and instead creates a folder even though one already exists. Example: I have file 123456 Action List.xlsx that I would like to go to folder 123456 Health Center. The first code will accomodate that but is extremely slow and gets slower as it goes along. Here is the second code:

@echo off &setlocal
for /f "delims=" %%i in ('dir /b /a-d *.xlsx') do (
set "filename1=%%~i"
setlocal enabledelayedexpansion
set "folder1=!filename1:~0,6!"
mkdir "!folder1!" 2>nul
move "!filename1!" "!folder1!" >nul
endlocal
)

Any help is appreciated.

@Squashman - I'll try to explain a little better...

123456 Action List.xlsx
123456 Reportcard.xlsx
123456 CHCUP.xlsx
123456 Combo3.xlsx

123457 Action List.xlsx
123457 Reportcard.xlsx
123457 CHCUP.xlsx
123457 Combo3.xlsx

Each month I end up with ~3300 files like this after running various macros. I have folders like "123456 Health Center" and "123457 MLK Center" already set up. What I'm trying to do is move all of those .xlsx files into the corresponding folder. That first code set works but like I said its slow. What its doing is looking to see if there are corresponding file and folder names based on first 6 characters. If there is it moves the file to that folder.

The second code is MUCH faster but it doesnt like the second part of the folder name i.e. "Health Center or MLK Center" from my examples and it then creates its own file with just the number portion i.e. 123456 or 123457 from my example.

Does that help?


Solution

  • Save this script as test.bat in a folder with other .bat files, and run from open Cmd Prompt. Replace dir value with the path to your folder with XLSX files. The script assumes, target folders in which the files are sorted are created in the dir folder. Let me know if any errors.

    @echo off
    setlocal enabledelayedexpansion
    set "dir=C:\XLSX_Folder"
    pushd "%dir%"
    for /f "tokens=*" %%I in ('dir /b /a:-d "*.xlsx"') do (
        if not exist "%%~nI" md "%%~nI" 2>nul
        move "%%I" "%%~nI" >nul )
    popd
    exit /b