Search code examples
sortingbatch-filecmd

Move Files to Folders with same name


I have 1000 files with the suffix -PRO1 and -PPR2 (1000 each) so I have 1000 folders with the same names but without the suffix...

For example I have a folder called Abstract_Colorful and I have the files Abstract_Colorful-PRO1 and Abstract_Colorful-PPR2 and so on...

I want to make a batch to be able to move all files automatically, I have this code (from another post)

@echo off 
setlocal enabledelayedexpansion
pushd "C:\Folders\"
for %%a in (*) do (
  set fldr=%%~na
  set fldr=!fldr:~0,4!
  md "!fldr!"
  move "%%a" "!fldr!"
)
popd
pause
exit

but what it does is that if the file has more than 4 characters it creates a folder with the first 4 chars... What I want to do is that the batch recognizes the filename and stops at the - and moves to the folder...

Thanks for your time :)


Solution

  • @echo off
    pushd "C:\Folders"
    rem Process all files in this folder separating the names at "-"
    for /F "tokens=1* delims=-" %%a in ('dir /B *.*') do (
       rem At this point %%a have the name before the "-" and %%b the rest after "-"
       rem Create the folder, if not exists
       if not exist "%%a" md "%%a"
       rem Move the file there
       move "%%a-%%b" "%%a"
    )
    popd