Skip to content

Instantly share code, notes, and snippets.

@trx1138
Created March 3, 2018 03:16
Show Gist options
  • Save trx1138/0c7d973a9a8a3fb10f60c820a72f96ff to your computer and use it in GitHub Desktop.
Save trx1138/0c7d973a9a8a3fb10f60c820a72f96ff to your computer and use it in GitHub Desktop.
extract srt from mkv container with ffmpeg (for synology)
#!/bin/bash
# Extract subtitles from each MKV file in the given directory
# If no directory is given, work in local dir
if [ "$1" = "" ]; then
DIR="."
else
DIR="$1"
fi
# Get all the MKV files in this dir and its subdirs
find "$DIR" -type f -name '*.mkv' | while read filename
do
# Find out which tracks contain the subtitles
ffmpeg -i "$filename" |& grep 'subrip' | while read subline
do
echo $subline
# Grep the number of the subtitle track
tracknumber=`echo $subline |& egrep -o "[0-9]{1,2}:[0-9]{1,2}" | head -1`
echo $tracknumber
# Get base name for subtitle
subtitlename=${filename%.*}
echo $subtitlename
# Extract the track to a .tmp file
`ffmpeg -i "$filename" -vn -an -map $tracknumber -f srt "$subtitlename.srt.tmp" > /dev/null 2>&1`
`chmod g+rw "$subtitlename.srt.tmp"`
# Do a super-primitive language guess: ENGLISH
langtest=`egrep -ic ' you | to | the ' "$subtitlename".srt.tmp`
trimregex=""
# Check if subtitle passes our language filter (10 or more matches)
if [ $langtest -ge 10 ]; then
`mv "$subtitlename.srt.tmp" "$subtitlename.en.srt"`
else
# Not our desired language: add a number to the filename and keep anyway, just in case
`mv "$subtitlename.srt.tmp" "$subtitlename.$tracknumber.srt" > /dev/null 2>&1`
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment