I need .bat that will make folders based on filenames and put files inside. I have names formatted like this:

string1 - string2 - string3 - string2 - string3_number.jpg

I find out command that will take 3 first strings as i needed, but cant make it work further. When i try to put this command into bat it makes only folder called "--".

for /F "tokens=1,2,3 delims=-" %%a in ('dir /B /A-D') do (set string1=%%a&set string2=%%b&set string3=%%c
md "%string1%-%string2%-%string3%")

putting @echo off and setlocal before this in .bat dont work can someone help make it right so it will make folders based on names and put files in. I read these posts but still can't even make folders:

up vote 3 down vote accepted

Because of delayedexpansion is required when setting and using a var in a (code block) it doesn't work.

But as you don't change the vars that isn't needed at all.

@Echo off & Setlocal EnableDelayedExpansion

for /F "tokens=1,2,3 delims=-" %%a in ('dir /B /A-D') do (
  set "Folder=%%a-%%b-%%c"
  Rem to remove the trailing space from the Folder
  set "Folder=!Folder:~0,-1!"
  If not exist "!Folder!\" MD "!Folder!"

To also move files that is the wrong approach, you should then 1st iterate the files and 2nd split them as above.

  • Well done @LotPings. Introduced in 1999... I never knew about Delayed Expansion. – Allen Jackson Aug 6 at 21:08

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.