使用.bat根据名称中的模式将文件排序到文件夹中

时间:2013-12-18 10:58:49

标签: windows batch-file cmd aggregate

考虑父文件夹

C:\Users\..\Parent

在父母下面有3个文件夹M1,M2,M3

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

在M1,M2,M3下有100个子文件夹。

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

同样适用于M2,M3。


在每个文件夹(MattP001M1..MattP100M1)下都有大量的.wav文件(平均值接近1500)。 这些wav文件在命名中有一个模式。 例如:有German_09mea4567_morename的20个文件和German_4132azzi_morename的15个文件,依此类推。 我正在使用这个脚本,根据(09mea4567)之后的独特部分将它们分组到文件夹中。

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

现在这适用于一个文件夹。我想对M1(MattP001M1,..,MattP100M1),M2,M3下的所有文件夹执行此操作。

请注意:这是一台机器上的设置。在另一台机器而不是德语机器上还有其他一些语言。

希望我让自己更清楚。

1 个答案:

答案 0 :(得分:1)

@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"
            )
        )
    )

目录创建和文件移动将回显到控制台。如果输出正确,请在echomd之前删除move命令以使其正常工作。