Skip to content

Instantly share code, notes, and snippets.

@f-o
Created May 23, 2026 21:02
Show Gist options
  • Select an option

  • Save f-o/38318835d112afb04620b4b9f2867184 to your computer and use it in GitHub Desktop.

Select an option

Save f-o/38318835d112afb04620b4b9f2867184 to your computer and use it in GitHub Desktop.
Simple bash script to help trim video files.
#!/usr/bin/env bash
# --- Flag parsing ---
SUBS=false
POSITIONAL=()
for arg in "$@"; do
case "$arg" in
--subs|-s) SUBS=true ;;
*) POSITIONAL+=("$arg") ;;
esac
done
INPUT="${POSITIONAL[0]}"
if [[ -z "$INPUT" || ! -f "$INPUT" ]]; then
echo "Usage: $0 [--subs|-s] <input_file.mp4|mkv>"
exit 1
fi
# --- Whisper check (only if --subs is set) ---
if [[ "$SUBS" == true ]]; then
if ! command -v whisper &>/dev/null; then
echo "Error: 'whisper' not found. Install it with:"
echo " pip install openai-whisper"
exit 1
fi
fi
BASENAME="${INPUT%.*}"
EXT="${INPUT##*.}"
echo "Input file: $INPUT"
[[ "$SUBS" == true ]] && echo "Subtitles: enabled"
echo ""
echo "Enter timestamps one by one (e.g. 01:02:14)."
echo "Press Enter with no input when done."
echo ""
generate_subs() {
local FILE="$1"
echo " Generating subtitles for: $FILE"
whisper "$FILE" --output_format srt --output_dir "$(dirname "$FILE")" &>/dev/null
if [[ $? -eq 0 ]]; then
echo " ✓ Subtitles saved: ${FILE%.*}.srt"
else
echo " ✗ Whisper failed for: $FILE"
fi
}
PREV="00:00:00"
SEGMENT=1
while true; do
read -rp "Segment $SEGMENT start: $PREV — end timestamp (or Enter to finish): " NEXT
if [[ -z "$NEXT" ]]; then
OUTPUT="${BASENAME}_segment$(printf '%02d' $SEGMENT).${EXT}"
echo " Exporting: $PREV → end → $OUTPUT"
ffmpeg -loglevel error -i "$INPUT" \
-ss "$PREV" \
-c:v libx264 -crf 18 -preset fast \
-c:a copy \
"$OUTPUT"
if [[ $? -eq 0 ]]; then
echo " ✓ Saved: $OUTPUT"
[[ "$SUBS" == true ]] && generate_subs "$OUTPUT"
else
echo " ✗ ffmpeg failed for segment $SEGMENT."
fi
echo "Done. $SEGMENT segment(s) exported."
break
fi
# Basic format validation
if ! [[ "$NEXT" =~ ^[0-9]{2}:[0-9]{2}:[0-9]{2}$ ]]; then
echo " Invalid format. Use HH:MM:SS (e.g. 01:02:14). Try again."
continue
fi
OUTPUT="${BASENAME}_segment$(printf '%02d' $SEGMENT).${EXT}"
echo " Exporting: $PREV → $NEXT → $OUTPUT"
ffmpeg -loglevel error -i "$INPUT" \
-ss "$PREV" -to "$NEXT" \
-c:v libx264 -crf 18 -preset fast \
-c:a copy \
"$OUTPUT"
if [[ $? -eq 0 ]]; then
echo " ✓ Saved: $OUTPUT"
[[ "$SUBS" == true ]] && generate_subs "$OUTPUT"
else
echo " ✗ ffmpeg failed for segment $SEGMENT."
fi
PREV="$NEXT"
((SEGMENT++))
echo ""
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment