Video – How to Order and Merge Many .ts Files?

macosmergevideo

I have many small files (about 500). They are in right order. I would like to merge them.
Linux commands are also welcome because I can compile them in my OS X.
The command cat *.ts > masi.ts does not work well. The result stops at some points. I am investigating why this occurs.
Some parts of the videos are not in order.

Names of parts of videos where each file has a prefix HRmasi453-27012016.mp4.ts

1.ts
2.ts
...
100.ts
101.ts
...
200.ts
...
300.ts

so the filename is HRmasi453-27012016.mp4-01.tsHRmasi453-27012016.mp4-300.ts.
The command cat *.ts > masi.ts does not organise the video in the sequential order.
I think I should make a list before of all items in order.
Then, merge.

Pseudocode

  1. Make a list of videos in order
  2. Merge cat items in list
    • Do something like filename = prefix + itemInList without creating a new list in the while loop.
    • cat filename >> result.ts

How can you join the many video files, .ts, files?

Best Answer

I need to preface this by saying having not worked with .ts files I do not know whether or not they can be simply concatenated using cat and as you saw because the are numerically named they get mixed up when using cat *.ts > masi.ts because it sorts lexicographically, so using a ordered list is in order. With that in mind, here is what I did to create a list of 500 numerically named .ts files and then concatenate them using the list.

I first created 500 numerically named .ts files containing the number of the .ts filename as a control. I used for i in {1..500}; do echo $i > $i.ts; done These weren't actually valid .ts files however it allowed me to have 500 files to work with and then see that they were concatenated in proper order when opening the combined.ts file to see an ordered numerical list within the file.

Since you already have the 500 .ts files, in Terminal do the following:

cd ts_files_directory
echo {1..500}.ts | tr " " "\n" > tslist
while read line; do cat $line >> combined.ts; done < tslist


Updated to include actual filename per your comment to my answer and your updated question.

The following assumes that the only numbers in itemInList with a leading 0 (zero) are e.g., 01...09 and that you change 500 in the {100..500} portion of the command to the actual count.

Change directory to that of which contains the .ts files.

cd ts_files_directory

The following two commands create the tslist file which is a numerically ordered list of the target filenames to be used with cat in order to avoid the lexicographical sorting issue.

echo 'HRmasi453-27012016.mp4-'{01..99}.ts | tr " " "\n" > tslist
echo 'HRmasi453-27012016.mp4-'{100..500}.ts | tr " " "\n" >> tslist

With the numerically ordered list created, use the following command line to concatenate based on the contents of the tslist file.

while read line; do cat $line >> combined.ts; done < tslist