Last active
August 10, 2017 12:14
-
-
Save ang3lkar/a2adbe973914bf724ec1bcc2b54e31a8 to your computer and use it in GitHub Desktop.
Rename subtitles according to their video file counterparts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Renames subtitles files according to tv shows names found in a directory | |
# Acceped syntaxes for season/episode are: 304, s3e04, s03e04, 3x04, Ep-04 (case insensitive) | |
# | |
# Installation: | |
# Put this gist somewhere in your $PATH, like /usr/local/bin/sub.sh | |
# Chmod +x it | |
# cd ~/YourTvShowsFolderContainingVideoAndSubtitleFiles | |
# sub | |
# | |
# Alternatively, add a function to your .bash_profile | |
# function sub() { | |
# /path/to/sub.sh | |
# } | |
# | |
# | |
# Usage: | |
# sub | |
# | |
# | |
# | |
# Note: zipfiles will be unzipped and .zip will be removed | |
# unzip files, maybe there are subtitles in it... | |
for f in *.zip; do | |
if [ -e "$f" ]; then | |
unzip "$f" | |
rm "$f" | |
fi | |
done | |
# switch into case insensitive | |
shopt -s nocasematch | |
# search subtitles | |
for f in *.{srt,ssa,sub} ; do | |
if [ -e "$f" ]; then | |
if [[ "$f" =~ s([0-9]+)e([0-9]+) || "$f" =~ ([0-9]+)x([0-9]+) || "$f" =~ ([0-9]+)([0-9][0-9]) ]]; then | |
echo "Found '$f'" | |
let SEASON="10#${BASH_REMATCH[1]}" # eventually delete leading 0 | |
EPISODE=${BASH_REMATCH[2]} | |
# search for a matching film | |
for movie in *.{mp4,avi,mkv} ; do | |
if [ -e "$movie" ]; then | |
if [[ "$movie" =~ ${SEASON}${EPISODE} || "$movie" =~ s0?${SEASON}e${EPISODE} || "$movie" =~ ${SEASON}x${EPISODE} || "$movie" =~ Ep\-${EPISODE} ]]; then | |
NEW_NAME=`echo "${movie%.*}.${f##*.}"` | |
if [ "$f" = "${NEW_NAME}" ]; then | |
echo " Already ok" | |
elif [ -e "${NEW_NAME}" ]; then | |
echo " A file named '${NEW_NAME}' already exists, skipping" | |
else | |
mv "$f" "${NEW_NAME}" | |
echo " Renamed '$f' to '${NEW_NAME}'" | |
fi | |
break; | |
fi | |
fi | |
done | |
fi | |
fi | |
done | |
# reswitch into case sensitive | |
shopt -u nocasematch | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment