I have several .pdf and .jpg-files that I need to move.

They're named something like this


* being some affix.

Now I want to move these files into folders like this

002\002 - 054\002-054*.pdf
042\042 - 021\042-021*.pdf

Some folders already exists, but in this naming scheme 002\002 - 054 Some Name\

I only want to create the folders as stated in the 2nd code snippet, when they don't already exists. If they already exists, I just want to move the files into the according folder.

Through some googling I was able to put something together

@echo off
for %%F in (*.pdf *.jpg) do call :subr "%%F"
exit /b

set filename=%1
move %1 %filename:~1,3%\%filename:~1,7%\
exit /b

But this doesn't consider the folders that already exist. What would be the best way to accomplish that?


You simply need to add a couple of lines to the subroutine:-

set filename=%1
Rem Check for existence of directories in target path
if not exist %filename:~1,3% md %filename:~1,3%
if not exist %filename:~1,3%\%filename:~1,7% md %filename:~1,3%\%filename:~1,7%
Rem Now the move can proceed
move %1 %filename:~1,3%\%filename:~1,7%\
exit /b

This will fail if there is an existing file with the same name as one of the directory paths that you need to create. You will need to decide how to handle this case, such as by adding an extension to the name or moving the file to another place.


Provided the folder have to be created in the current dir
and the 2nd level folder has - between the numbers:

@echo off
for /f "delims=" %%F in (
  'Dir /b *.pdf *.jpg^|findstr "^[0-9][0-9][0-9]-[0-9][0-9][0-9]" '
) do call :subr "%%F"
exit /b

set "file=%~n1"
set "fold=%file:~0,3%\%file:~0,3% - %file:~4,3%\"
if not exist "%fold%" md "%fold%"
move %1 "%fold%"

The changed for and dir |findstr are to ashure only files starting with the number pattern 999-999 are processed.
As md creates intermediate folders only one md is needed.

  • What if want to check the folders name with a wildcard? Would I write it like this if not exist "%fold%"* md "%fold%" – Claypenguin Apr 24 '18 at 14:04
  • The comment was somehow aborted, it's unclear to me what you are asking. – LotPings Apr 24 '18 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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