Shaz
Shaz

Reputation: 15867

Move files from folder to new folder based on # of files

This may be a specific case but given the right code I'm sure many could take from it.

I have thousands of files in one folder that need to be split up into multiple folders. Each folder needs to have 1 more file than the one before it and needs to be named as such. Each folder needs to have at least X amount of files. For example, here is what the end results might look like if each folder had to have at least 1 file:

U:\Batch\Original\ -->
    file1.xml
    file2.xml
    file3.xml
    file4.xml
    file5.xml
    file6.xml

U:\Batch\Processed\ -->
    folder1.1 -->
        file1.xml
    folder2.2 -->
        file2.xml
        file3.xml
    folder3.3 -->
        file4.xml
        file5.xml
        file6.xml

I have started attempting this on my own but I feel I am way off. Say I needed at least 1000 files in each folder. How would one go about doing this in a .bat program?

Upvotes: 2

Views: 673

Answers (2)

rojo
rojo

Reputation: 24476

Here you go. This should handle it.

@echo off
setlocal enabledelayedexpansion
set /a "minimum=1000, outer=minimum, inner=1"
set folder_prefix=folder
call :mkfolder

:: dir list, order by name, exclude directories, exclude this batch script
for /f "delims=" %%I in ('dir /b /o:n /a:-d ^| findstr /v "%~nx0"') do (
    if !inner! GTR !outer! (
        set /a "inner=1, outer+=1"
        call :mkfolder
    )
    copy "%%I" "!folder!" >NUL
    set /a "inner+=1"
)

:: rename final directory to reflect the number of files contained within
for /f "delims=" %%I in ("%folder%") do set "to=%%~dpnI"
set /a "inner-=1"
ren "%folder%" "%to%.%inner%"


goto :EOF

:mkfolder
set folder=%folder_prefix%!outer!.!outer!
if not exist "!folder!" mkdir "!folder!"
goto :EOF

Upvotes: 1

James L.
James L.

Reputation: 9461

You are on the right track. To demonstrate, first we need to create a few files to work with:

md c:\y
cd /d c:\y
for %i in (1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30) do echo.>%i.txt

Now we can run the following batch file from c:\y to create sub folders and copy the files as you indicated (but with 3 as the minimum files in this example):

@echo off

setlocal EnableDelayedExpansion

set cnt=1
set fldr=1
set min=3

for %%i in (*.txt) do (
  if !cnt! GTR !min! (
    set /a cnt-=1
    ren folder!fldr! folder!fldr!.!cnt!
    set cnt=1
    set /a fldr+=1
    set /a min+=1
  )

  md folder!fldr! > nul 2>&1

  copy "%%i" folder!fldr!

  set /a cnt+=1
)

set /a cnt-=1
ren folder!fldr! folder!fldr!.!cnt!

Upvotes: 1

Related Questions