Skip to content

Instantly share code, notes, and snippets.

@fevangelou
Last active January 25, 2024 07:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fevangelou/48da813ac1d5d0d207ff0acab1c09df2 to your computer and use it in GitHub Desktop.
Save fevangelou/48da813ac1d5d0d207ff0acab1c09df2 to your computer and use it in GitHub Desktop.
Extract Subtitles From MKV Files
#!/bin/bash
# /**
# * @version 1.0
# * @name Extract Subtitles From MKV Files
# * @author Fotis Evangelou
# * @date March 2023
# * @license WTFPL (http://www.wtfpl.net)
# */
# USAGE
# - Download this script and place it in a folder that directly lists MKV files
# - Make it executable: $ chmod +x extract_subtitles_from_MKV_files.sh
# - Ensure mkvtoolnix is installed on your system
# (e.g. run "apt install mkvtoolnix" on Debian based OSes or "brew install mkvtoolnix" on macOS etc.)
# - Simply execute the script: $ ./extract_subtitles_from_MKV_files.sh
# TO DO
# - Execute rescursive search for MKV files and in a case-insensitive way
# - Pass directory path as option in script
# - Bake support for "HDMV PGS", "ASS" or other subtitle types by utilizing FFMPEG
# One liner version - for direct use on the terminal
# for F in *.mkv; do MKV=$(echo $F | sed -e "s/\.mkv$//"); SUBS=$(mkvmerge -i "$MKV.mkv" | grep "SubRip/SRT" | cut -d ' ' -f3 | tr -d ':'); for SUB in $SUBS; do mkvextract tracks "$F" $SUB:"${MKV}_$SUB.srt"; done; done
# This was created in response to another Gist that returned high in search results for "Extract Subtitles From MKV Files":
# https://gist.github.com/kampfgnu/bb7be04b624ed5ddf65d6e7c54f9ce2e
# Expanded version - for use in this script
for F in *.mkv; do
# Get the file name without its extension
MKV=$(echo $F | sed -e "s/\.mkv$//")
# Create array of subtitle track IDs that match the type "SubRip/SRT"
SUBS=$(mkvmerge -i "$MKV.mkv" | grep "SubRip/SRT" | cut -d ' ' -f3 | tr -d ':')
# Extract subtitles for each MKV file
echo "Extracting SubRip/SRT subtitles from $F..."
for SUB in $SUBS; do
echo "- Extractive subtitle track ID $SUB..."
mkvextract tracks "$F" $SUB:"${MKV}_$SUB.srt"
echo "...done"
echo ""
done
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment