Skip to content

Instantly share code, notes, and snippets.

@fffonion
Last active August 26, 2023 21:10
Show Gist options
  • Save fffonion/2ca573e48a78b7f7e09d76a7fad5fa08 to your computer and use it in GitHub Desktop.
Save fffonion/2ca573e48a78b7f7e09d76a7fad5fa08 to your computer and use it in GitHub Desktop.
Extract subtitles track
#!/bin/bash
f="$1"
IFS=$'\r\n'
filename="${f%.*}"
bf=$(basename "$filename")
options=()
moptions=()
for s in $(ffprobe "$f" -show_entries stream=index,codec_type,codec_name:stream_tags=language,title -of compact 2>/dev/null|grep "codec_type=subtitle"); do
# stream|index=5|codec_type=subtitle|tag:language=jpn|tag:title=官方日文字幕
stream=$(echo $s|grep -oP 'index=\d+'|grep -oP '\d+')
lang=$(echo $s|grep -oP 'tag:language=.{3}'| cut -d= -f2)
if [[ $lang == "chi" ]]; then
if [[ ! -z $(echo "$s"|grep -P "(Traditional|繁)") ]]; then
lang=cht
else
lang=chs
fi
fi
if [[ ! -z "$lang" ]]; then
lang=".$lang"
fi
title=$(echo $s|grep -oP "title=.+"|cut -d= -f2)
if [[ ! -z "$title" ]]; then
title=".$title"
fi
format=$(echo $s|grep -oP "codec_name=[^:|]+"|cut -d= -f2)
if [[ ! -z $(echo $s|grep subrip) ]]; then
format=srt
elif [[ ! -z $(echo $s|grep hdmv_pgs_subtitle) ]]; then
format=sup
elif [[ ! -z $(echo $s|grep dvd_subtitle) ]]; then
moptions+=("$stream:${bf}${title}${lang}.sub")
continue
else
format=ass
fi
echo $s $stream $title $lang
options+=(-map "0:$stream" -c copy "${bf}${title}${lang}.${format}")
done
if [[ ${#options[@]} -gt 0 ]]; then
ffmpeg -i "$f" -y ${options[@]}
echo "ffmpeg -i -y $f ${options[@]}"
fi
if [[ ${#moptions[@]} -gt 0 ]]; then
mkvextract tracks "$f" ${moptions[@]}
echo "mkvextract tracks $f ${moptions[@]}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment