Batch concatenate multiple .ts files to single file in order

Viewed 265

I am trying to merge multiple .ts files into a single one.

The below script merges files in order if file numbers are less than 10 i.e. A1.ts, A2.ts, ...., A9.ts:

copy /b *.ts joined_files.ts

However, when file numbers are greater than 100, they get merged in the order A1.ts, A10.ts,..., A2.ts, A20.ts, and so on. (Not numerically as expected)

To deal with this issue, I am trying to use a for loop and a variable name iterating over the numbers as below:

:MainProcessNew

set "BaseName=A"
set "FileNumber=1"

:FileNameLoop
set /A FileNumber+=1
copy /b "%BaseName%%G%.ts" joined_files.ts
if exist "%BaseName%%FileNumber%.ts" goto FileNameLoop

I found this link to be relevant but I could not follow: Link

I am very new to batch scripts. Please help me out !

1 Answers

One thing you can do is to extract the numbers. In your case it seems easy enough as you have a pattern which is basename, number, extension.

So we can then extract all the numbers, match them with each other to find the highest number, then sort them using for /l:

@echo off
set max=
set "bn=A"
setlocal enabledelayedexpansion
for /f "delims=" %%i in ('dir /b "*.ts"') do (
    set "nm=%%~ni"
    set "nm=!nm:%bn%=!
    if not defined max set max=!nm!
    if !nm! gtr !max! set max=!nm!
)
for /l %%n in (1,1,%max%) do if exist %bn%%%n.ts echo %bn%%%n.ts

This will simply print each name to the screen to show you that it is able to sort it. In your case you can then change the last line to:

(for /l %%n in (1,1,%max%) do if exist %bn%%%n.ts type %bn%%%n.ts)>joined_files.ts
Related