Search code examples
windowsbatch-filecommand-linemkv

Batch combine video files in a folder and subfolders


I have about 200 folders filled with MPG split files. I wanted to join files together of each folder. I found this BATCH script in other question on stackoverflow.

@echo off &setlocal enabledelayedexpansion
cd /d "%sourcefolder%"
set "line="
for %%a in (*.mpg) do set line=!line! +"%%~a"
"C:\Program Files\MKVToolNix\mkvmerge.exe" -o "Output.mkv" %line:~2%

Combine mkv's in Windows (automated, not using a GUI)

It works great but the problem is, i have to paste .bat file in about 200 folders and then run it about 200 times.

Can someone please help me. How can i run this file from root folder to merge/join all the files in subfolders and create new "output.mkv" file in either each subfolder or to a new folder like "/OutputVideos" with possibly a number increment in name or the same name as subfolder.

I would really appreciate the help. Thanks


Solution

    • Use for-loop to enumerate recursively /r through subdirectories /d
    • Change the working directory to the loop variable
    • Enumerate the .mpg files and concatenate the names in a variable (use delayed expansion)
    • Invoke mkvmerge with that variable (note that it starts with a space and + so we should extract its contents starting with index 2, the index is 0-based which means that the first character has index 0 and the third character we need has index 2)

    Put the code in concatenate.bat file in the base folder, the batch file will process all subfolders.

    @echo off
    setlocal enableDelayedExpansion
    
    set mkvmerge="C:\Program Files\MKVToolNix\mkvmerge.exe"
    
    for /d /r %%D in (*) do (
        pushd %%D
        set files=
        for %%F in (*.mpg) do set files=!files! + ^( "%%F" ^)
        if not "!files!"=="" %mkvmerge% -o "output.mkv" !files:~2!
        popd
    )
    pause