Skip to content

Instantly share code, notes, and snippets.

@Svision
Created August 3, 2022 18:03
Show Gist options
  • Save Svision/dd4bb5d96cbc5b134f302d0cca3513a6 to your computer and use it in GitHub Desktop.
Save Svision/dd4bb5d96cbc5b134f302d0cca3513a6 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Copy and enhanced from
# https://gist.github.com/colinux/799510/7611d94545a66cdc21bf589df3f4d0b0813419b6#file-subtitles-renamer-sh
# Renames subtitles files according to tv shows names found in a directory
# Acceped syntaxes for season/episode are: 304, s3e04, s03e04, 3x04 (case insensitive)
#
# Note: zipfiles will be unzipped and .zip will be removed
#
# There are bashisms to work with regular expressions,
# so you really need bash or a shell compatible
cd "/volume1/video/TV Shows/"
for tv_shows in */ ; do
cd "/volume1/video/TV Shows/$tv_shows"
for episode in */ ; do
cd "./$episode"
# 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,ass} ; 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} ]]; then
sub_suffix=${f: -3}
NEW_NAME=`echo "${movie%.*}"."${sub_suffix}"`
if [ "$f" = "${NEW_NAME}" ]; then
echo " Already ok"
elif [ -e "${NEW_NAME}" ]; then
echo " A file named '${NEW_NAME}' already exist, skipping"
else
mv "$f" "${NEW_NAME}"
echo " Renamed '$f' in '${NEW_NAME}'"
fi
break;
fi
fi
done
fi
fi
done
done
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