krkr
2/25/2018 - 9:37 PM

Renames subtitles files according to tv shows names

Renames subtitles files according to tv shows names

#!/bin/bash -eu
#
# Renames subtitles files according to tv shows names found in the current directory
# Accepted syntaxes for season/episode: s3e04, s03e04, 3x04 (case insensitive)
#

# switch into case insensitive
shopt -s nocasematch

# search subtitles
for f in *.{srt,ssa,sub}; do
  if [ ! -e "$f" ]; then
    continue
  fi
  if [[ "$f" =~ s([0-9]+)e([0-9]+) || "$f" =~ ([0-9]+)x([0-9]+) ]]; then

    let SEASON="10#${BASH_REMATCH[1]}" # eventually delete leading 0
    EPISODE=${BASH_REMATCH[2]}

    # search for a matching film
    for movie in *.{avi,mkv} ; do
      if [ ! -e "$movie" ]; then
        continue
      fi
      if [[ "$movie" =~ s0?${SEASON}e${EPISODE} || "$movie" =~ ${SEASON}x${EPISODE} ]]; then
        echo "Match for movie s${SEASON}e${EPISODE}"

        NEW_NAME=`echo "${movie%.*}".srt`
        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

    done
  fi
done

# reswitch into case sensitive
shopt -u nocasematch