Matt
Matt

Reputation: 171

Sorting files into folders based on a pattern in their name using .bat

Consider a parent folder

C:\Users\..\Parent

Under parent there are 3 folders M1,M2,M3

C:\Users\..\Parent\M1
C:\Users\..\Parent\M2
C:\Users\..\Parent\M3.

Under M1,M2,M3 there is 100 sub folders.

C:\Users\..\Parent\M1\MattP001M1
C:\Users\..\Parent\M1\MattP002M1
so on till 
C:\Users\..\Parent\M1\MattP100M1.

Similarly for M2,M3 as well.


Under every folder(MattP001M1..MattP100M1) there are a ton of .wav files(close to 1500 on an avg). These wav files have a pattern in their naming. e.g: There are 20 files with German_09mea4567_morename and 15 files with German_4132azzi_morename and so on. I am using this script on them to group them in folders based on the unique part after(09mea4567).

SETLOCAL ENABLEDELAYEDEXPANSION
for %%a in (*.wav) do (
set f=%%a
set g=!f:~7,8!
md "!g!" 2>nul
move "%%a" "!g!"
)

Now this is fine for one folder. I want to do this for all the folders under M1(MattP001M1,..,MattP100M1), M2, M3.

Please note: This is a setup on one machine. On a different machine instead of German there is some other language.

Hope i made myself much clearer enough.

Upvotes: 1

Views: 349

Answers (1)

MC ND
MC ND

Reputation: 70923

@echo off

    rem Prepare environment
    setlocal enableextensions disabledelayedexpansion

    rem configure where to start
    set "root=c:\somewhere"

    rem For each file under root that match indicated pattern
    for /r "%root%" %%f in (*_*_*.wav) do (

        rem Split the file name in tokens using the underscore as delimiter
        for /f "tokens=2 delims=_" %%p in ("%%~nf") do (

            rem Test if the file is in the correct place
            for %%d in ("%%~dpf.") do if /i not "%%~p"=="%%~nd" (

                rem if it is not, move it where it should be
                if not exist "%%~dpf\%%~p"  echo md "%%~dpf\%%~p"
                echo move "%%~ff" "%%~dpf\%%~p"
            )
        )
    )

Directory creation and file move are echoed to console. If output is correct, remove echo command before md and move to make it work.

Upvotes: 1

Related Questions