简体   繁体   中英

Sorting files into folders by file 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. eg: 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 this time

@ECHO OFF &SETLOCAL
for /d %%x in ("x:\parent folder\folder*") do (
    pushd "%%~x"
    for %%a in (*.wav) do for /f "tokens=1-4delims=_" %%b in ("%%~na") do (
        md "%%~e" 2>nul
        move "*_*_*_%%~e%%~xa" "%%~e" 2>nul
    )
    popd
)

This Solved my problem. Thanks to solution by MC ND

@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"  md "%%~dpf\%%~p"
            move "%%~ff" "%%~dpf\%%~p"
        )
    )
)

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