Skip to content

Instantly share code, notes, and snippets.

@JoeSz
Forked from cinatic/extractMkvSubtitles.sh
Last active November 19, 2022 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoeSz/091adce4dac42b3458ed21cc1c11b001 to your computer and use it in GitHub Desktop.
Save JoeSz/091adce4dac42b3458ed21cc1c11b001 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
path=$PWD
echo
echo -e "\033[33mWould you like to extract subtitles from each MKV file in the directory?\033[m"
echo -e "Folder: ${path}"
echo -e "(yes/no)"
read -p ""
if [ "$REPLY" != "yes" ]; then
echo -e '\033[38;2;255;0;0mExited by the user.\033[m'
# https://codefather.tech/blog/exit-bash-script/
exit
fi
# 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 only
find "$DIR" -type f -maxdepth 1 -name '*.mkv' | while read filename
# 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"
echo Extracting: $subtitlename
# add language check if you like e.g.:
# if [ "$language" == "ger" ] || [ "$language" == "chiSimplified" ]; then
mkvextract tracks "$filename" $tracknumber:"$subtitlename.srt"
`chmod g+rw "$subtitlename.srt"`
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment