简体   繁体   中英

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?

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)

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

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!
) 
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM