Friday, May 10, 2024
3
rated 0 times [  3] [ 0]  / answers: 1 / hits: 1888  / 2 Years ago, sun, february 20, 2022, 12:26:48

I like to create a Bash script to concatenate MP4 files using FFmpeg, in batches of 5 files at a time for a directory with 100 MP4 files, so that afterwards there would be 20 files like:


001_005.mp4, 006_010.mp4, and so on...


instead of just 1 file consisting of all 100 files.


Contents of mylist.txt:


file 001.mp4
file 002.mp4
file 003.mp4
file 004.mp4
file 005.mp4
............
file 099.mp4
file 100.mp4

Though I've found a command that works just fine (from this StackOverflow thread), it would create only 1 file consisting all 100 files.


#!/bin/bash

cd /home/admn/Downloads/MP4_Files;

# Create mylist.txt:
for f in *.mp4
do
echo "file $f" >> mylist.txt
done;

# Concatenate files:
ffmpeg -f concat -safe 0 -i mylist.txt -c copy output.mp4;

So, how do I modify the ffmpeg command so that it concat in batches of 5 files at a time.


All the files have exact same resolution (1080p), audio, and video codecs.


OS: Ubuntu MATE 21.04


ffmpeg version: 4.3.2-0+deb11u1ubuntu1


More From » command-line

 Answers
4

I think the following script will work.



  • First try it as it is and check that it seems to do what you want

  • Then remove echo from the line with ffmpeg to make it do its thing.


Check that the content of the temporary files xaa' ... xat` matches the names (and content) of the output files.


#!/bin/bash

> mylist.txt
for f in *.mp4
do
echo "file '$f'" >> mylist.txt
done

< mylist.txt sort -t ' -n -k2 | split -l 5

k=1
for j in x*
do
inc=$(wc -l "$j" | cut -d ' ' -f 1)
m=$(printf "%03d" $((k)))
n=$(printf "%03d" $((k+inc-1)))
name="${m}_${n}.mp4"
echo ffmpeg -f concat -safe 0 -i "$j" -c copy "$name"
k=$((k+5))
done

[#1501] Monday, February 21, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
oredoise

Total Points: 66
Total Questions: 116
Total Answers: 111

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
;