Skip to content

Instantly share code, notes, and snippets.

@cinatic
Last active December 12, 2022 17:05
Show Gist options
  • Save cinatic/eb99c40f8725a2b224803e9d86b8fc92 to your computer and use it in GitHub Desktop.
Save cinatic/eb99c40f8725a2b224803e9d86b8fc92 to your computer and use it in GitHub Desktop.
Extract Subtitles from mkv
#!/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
mkvmerge -J $filename | jq -r '
.tracks |
map((.id | tostring) + " " + .properties.language + .properties.track_name + " " + .codec) |
join("\n")' | grep 'SubRip' | while read subline
do
# Grep the number of the subtitle track
tracknumber=`echo $subline | cut -d' ' -f1`
language=`echo $subline | cut -d' ' -f2`
# Get base name for subtitle
subtitlename="${filename%.*}_$language"
# add language check if you like e.g.:
# if [ "$language" == "ger" ] || [ "$language" == "chiSimplified" ]; then
`mkvextract tracks "$filename" $tracknumber:"$subtitlename.srt" > /dev/null 2>&1`
`chmod g+rw "$subtitlename.srt"`
done
done
@wernersbacher
Copy link

Line 15 should be mkvmerge -J "$filename", so paths with spaces still work (mkvmerge cant handle them)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment