Takyon
Takyon

Reputation: 21

Batch move files to new subfolders based on name

I'm using Windows 7 and I have half a million images stored in one folder "C:\capture". These images forms 330 image sequences and they are named as follows:

1.0000000000.png 
...
1.0000003299.png
... ...
330.0000000000.png
...
330.0000000010.png

I would like to move these into 330 subfolders named after the first part of the names.

C:\capture\1\1.0000000000.png 
...
C:\capture\1\1.0000003299.png
... ...
C:\capture\330\330.0000000000.png
...
C:\capture\330\330.0000000010.png

So I'm basically only interested in everything before the first '.' in the names. How do I write a batch file that creates the subfolders and moves the corresponding files into them?

Upvotes: 2

Views: 2338

Answers (3)

Albert F D
Albert F D

Reputation: 529

Taking my inspiration from sokins answer, I'll weigh in with this effort...

@echo off
setlocal enabledelayedexpansion

for %%i in (C:\capture\*.png) do (
    for /f "tokens=3 delims=.\" %%a in ('echo %%i') do (
    set prefix=%%a
    if not exist C:\capture\!prefix! md C:\capture\!prefix!
    move "%%i" C:\capture\!prefix!
) 
)

Upvotes: 0

sokin
sokin

Reputation: 844

Here is a more general batch script, that is boundary agnostic, in the sense that it will automatically decide how many subfolders have to be created, based on the "prefixes" of the images, so you don't have to modify it in case the number of image sequences changes.

@echo off

set DIR="C:\capture"
pushd %DIR%
setlocal ENABLEDELAYEDEXPANSION
for %%g in (*.png) do (
    set t=%%~nxg
    for /F "delims=." %%a in ("!t!") do (
        if not exist %%a (md %%a)
        move !t! %%a > nul
    )
)
endlocal
popd

Upvotes: 3

MC ND
MC ND

Reputation: 70923

To be executed from command line inside the directory to be processed (better if you try with a copy)

for /l %a in (1 1 330) do (md %a 2>nul & if exist %a\ move /y "%a.*.png" %a\ )

If you want to use it inside a batch file, percent signs need to be escaped, replacing all %a with %%a

for /l %%a in (1 1 330) do (
    md %%a 2>nul 
    if exist %%a\ move /y "%%a.*.png" %%a\ 
)

It will generate all the prefixes and for each one execute a move command to move the matching files to the final folder (previously created)

Upvotes: 4

Related Questions