Skip to content

Instantly share code, notes, and snippets.

@farzadhallaji
Last active October 22, 2023 20:29
Show Gist options
  • Save farzadhallaji/87904aa58d7497ca2cc847b4e2e73998 to your computer and use it in GitHub Desktop.
Save farzadhallaji/87904aa58d7497ca2cc847b4e2e73998 to your computer and use it in GitHub Desktop.
trim video
#!/bin/bash
# Check if ffmpeg is installed
command -v ffmpeg >/dev/null 2>&1 || { echo >&2 "ffmpeg is required but it's not installed. Exiting."; exit 1; }
# Check for valid number of arguments
if [ "$#" -ne 4 ]; then
echo "Usage: $0 input.mp4 start_time end_time output_base_path"
echo "Time format: HH:MM:SS or MM:SS"
exit 1
fi
INPUT_FILE="$1"
START_TIME="$2"
END_TIME="$3"
OUTPUT_BASE_PATH="$4"
# Extracting the file name without the extension
BASE_NAME=$(basename -- "$INPUT_FILE")
FILE_NAME="${BASE_NAME%.*}"
# Replacing colons with dots in start and end times to make them file-name friendly
START_TIME_FILE=$(echo "$START_TIME" | tr ':' '.')
END_TIME_FILE=$(echo "$END_TIME" | tr ':' '.')
# Creating a unique output file name based on input file, start time, end time, and an index
INDEX=1
OUTPUT_FILE="$OUTPUT_BASE_PATH/$FILE_NAME"_trim"$INDEX"_"$START_TIME_FILE"-"$END_TIME_FILE".mp4
while [ -f "$OUTPUT_FILE" ]; do
INDEX=$((INDEX+1))
OUTPUT_FILE="$OUTPUT_BASE_PATH/$FILE_NAME"_trim"$INDEX"_"$START_TIME_FILE"-"$END_TIME_FILE".mp4
done
# Function to convert HH:MM:SS to seconds
time_to_seconds() {
time=$1
hours=$(echo $time | cut -d':' -f1)
minutes=$(echo $time | cut -d':' -f2)
seconds=$(echo $time | cut -d':' -f3 | awk '{printf "%.6f", $0}')
total_seconds=$(echo "$hours * 3600 + $minutes * 60 + $seconds" | bc)
echo $total_seconds
}
# Calculate duration for the trimmed part
START_TIME_SECONDS=$(time_to_seconds "$START_TIME")
END_TIME_SECONDS=$(time_to_seconds "$END_TIME")
DURATION=$(echo "$END_TIME_SECONDS - $START_TIME_SECONDS" | bc)
ffmpeg -i "$INPUT_FILE" -ss "$START_TIME" -t "$DURATION" -c:v copy -c:a copy "$OUTPUT_FILE"
echo "Trimmed video saved as $OUTPUT_FILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment