Batch create folder and move files with same prefix

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
lupita
Posts: 1
Joined: 12 Jul 2017 02:35

Batch create folder and move files with same prefix

#1 Post by lupita » 12 Jul 2017 02:41

Hi everybody.
I need to move several files to a new folder with same prefix name (4 Initial Characters). For example:

INPUT
9087310.pdf
9087411.txt
9087512.dwg

9088613.pdf
9088714.txt
9088815.dwg

9089416.pdf
9089517.txt
9089618.dwg

OUTPUT
folder 9087 (9087310.pdf 9087411.txt 9087512.dwg)
folder 9088 (9088613.pdf 9088714.txt 9088815.dwg
folder 9089 (9089416.pdf 9089517.txt 9089618.dwg)

I want to do this with more than 200 files:
Thank you in advance.

penpen
Expert
Posts: 2009
Joined: 23 Jun 2013 06:15
Location: Germany

Re: Batch create folder and move files with same prefix

#2 Post by penpen » 12 Jul 2017 09:34

This might help you (untested - writing on my mobile phone):

Code: Select all

@echo off
setlocal enableExtensions disableDelayedExpansion
for %%a in (*.*) do (
   set "file=%%~na"
   setlocal enableDelayedExpansion
   set "prefix=!file:~0,4!"
   if not exist "!prefix!" md "!prefix!"
   for %%b in ("!prefix!") do (
      set "attributes=%%~ab"
      if not "!attributes!" == "!attributes:d=!" (
         echo(Error: Needed Directory name is blocked by a file.
      ) else (
         move "!file!" "!prefix!"
      )
   )
   endlocal
)
goto :eof


penpen

Post Reply