Skip to content

Instantly share code, notes, and snippets.

@DocX
Created March 16, 2025 14:45
Show Gist options
  • Save DocX/32081f6e1ebb34d768632cba69a43a9d to your computer and use it in GitHub Desktop.
Save DocX/32081f6e1ebb34d768632cba69a43a9d to your computer and use it in GitHub Desktop.
ffmpeg split video to segments script
# Use:
# split_video INPUT_FILE OUTPUT_FILE_PREFIX HH:MM:SS HH:MM:SS ...
#
# Description:
# Splits video segements between provided timestamps,
# omitting start (00:00:00 to first timestamp) and end (last timestamps to end of video)
split_video() {
input_file="$1"
output_file_name="$2"
shift
shift
# Convert timestamps array to seconds and store both formats
declare -a times_hms=("$@")
declare -a times_seconds
for t in "${times_hms[@]}"; do
seconds=$(echo "$t" | awk -F: '{ print ($1 * 3600) + ($2 * 60) + $3 }')
times_seconds+=($seconds)
done
# Process segments between timestamps (skip first and last segments)
for ((i=0; i<${#times_seconds[@]}; i++)); do
start_time="${times_hms[i]}"
end_time="${times_hms[i+1]}"
# Calculate duration
duration=$(echo "${times_seconds[i+1]} - ${times_seconds[i]}" | bc)
# Generate output filename using timestamps
output_file="$output_file_name ${start_time}-${end_time}.mp4"
# Replace colons with underscores for filename
output_file=$(echo "$output_file" | tr ':' '_')
echo "Creating segment from $start_time to $end_time"
ffmpeg -ss "$start_time" -i "$input_file" -t "$duration" -c copy -reset_timestamps 1 "$output_file"
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment