Ruben Laguna's blog

Jul 5, 2007 - 2 minute read - avi avi_files files linux normalize rename script shows srt_files tv

Scripts to rename avi files from TV Shows

If you got a lot of ill-named files like:

$ ls
S01E03.The.Sopranos.S01E03.Denial.Anger.Acceptance.avi
The.Sopranos.1x04.Meadowlands.avi
The.Sopranos.S01E01.The.Sopranos.avi
The.Sopranos.S01E02.46.Long.avi
The.Sopranos.S01E06.Pax.Soprana.avi
The_Sopranos.105.College.avi

that your divx player can’t sort properly and you want to end up with something like:

$ ls
1x01.avi  1x02.avi  1x03.avi  1x04.avi  1x05.avi  1x06.avi  

you can use the following script in this way:

cd /path/to/avi/files
../script.sh|sh

and if you want to do the same thing to srt files then:

cd /path/to/srt/files
../script.sh srt|sh

As an example the script will normalize any of the following patterns S01E03, 103,1x03, or just 03 to 1x03.

The contents of script.sh are:

#!/bin/bash
ext=$1
if [ ! $ext ]; then
ext="avi"
fi
FILES=\`find . -iname "*.$ext" -printf "%p\n"\`
IFS="
"
for i in $FILES; do

dirname=\`dirname $i\`
g=\`echo $i|perl -e '<STDIN> =~ m/S\d?(\d)E (\d+)/i; $1 and print $1 . "x" . $2'\`

if [ ! $g ]; then
g=\`echo $i|perl -e '<STDIN> =~ m/(\d)x(\d\d)/i; $1 and print $1 . "x" . $2'\`
fi
if [ ! $g ]; then
g=\`echo $i|perl -e '<STDIN> =~ m/(\d)(\d\d)/i; $1 and print $1 . "x" . $2;'\`
fi
if [ ! $g ]; then
g=\`echo $i|perl -e '<STDIN> =~ m/(\d\d)/i; $1 and print "1x" . $1'\`
fi

if [ $g ]; then
g="$dirname/$g.$ext"
if [[ "$g" != "$i" ]]; then
echo "if [ ! -e \"$g\" ]; then mv \"$i\" \"$g\"; fi"
fi
fi

done

The script is also available as a gist