Split Video – How to Split Video File into Pieces with FFmpeg

bashffmpegshell-script

When you want to extract two minutes of a video file from minute 2 to minute 4, you will use command

ffmpeg -i input.mpg -sameq -ss 00:02:00 -t 00:02:00 output.mpg

I'd like to split the video into two minutes chunks. I have an idea to use a bash script, but there are a few errors.

for i in seq 50;
do ffmpeg -i input.mpg -sameq -ss 00:`expr $i \* 2 - 2`:00 -t 00:02:00 output.mpg; done

Do you know how to correct the errors in script that are where I use $i expression? Or is there some better solution?

Best Answer

You forgot to use backticks - or better: $( ) subshell - in the seq invocation. This works:

for i in $( seq 50 );
do ffmpeg -i input.mpg -sameq -ss 00:`expr $i \* 2 - 2`:00 -t 00:02:00 output.mpg; done

Another thing is that you probably don't want output.mpg to be overwritten in each run, do you? :) Use $i in the output filename as well.

Apart from that: In bash, you can just use $(( )) or $[ ] instead of expr - it also looks more clear (in my opinion). Also, there is no need for seq - brace expansion is all you need to get a sequence. Here's an example:

for i in {1..50}
 do ffmpeg -i input.mpg -sameq -ss 00:$[ i* 2 - 2 ]:00 -t 00:02:00 output_$i.mpg
done

Another good thing about braces is that you can have leading zeros in the names (very useful for file sorting in the future):

for i in {01..50}
 do ffmpeg -i input.mpg -sameq -ss 00:$[ i* 2 - 2 ]:00 -t 00:02:00 output_$i.mpg
done

Notice as well, that i*2 - 2 can be easily simplified to i*2 if you just change the range:

for i in {00..49}
 do ffmpeg -i input.mpg -sameq -ss 00:$[ i*2 ]:00 -t 00:02:00 output_$i.mpg
done