Skip to content

Instantly share code, notes, and snippets.

@JudsonHat
Last active March 25, 2016 15:30
Show Gist options
  • Save JudsonHat/bfc7e338b52f10ce4b90 to your computer and use it in GitHub Desktop.
Save JudsonHat/bfc7e338b52f10ce4b90 to your computer and use it in GitHub Desktop.
Script to find subtitles that do not have a matching video file, then delete it
#!/bin/bash
# Usage
# /bin/bash ./remove_abandoned_subtitles.sh /path/to/media
if [ -z "${BASH_VERSINFO}" ]; then
echo "ERROR: You must execute this script with BASH"
exit
fi
# get the file name. try the command line first
if [ "$1" != "" ]; then
media_dir="$1"
else
media_dir=/path/to/media
fi
# check if media directory is legit
if [ ! -d "$media_dir" ]; then echo "Media directory "$media_dir" doesn't exist. Try again."; exit; fi
log="$HOME/.deletedsubtitles/subtitleListToRemove.tmp"
if [ -f $log ]; then rm $log; fi
backups=$HOME/.deletedsubtitles/remove_abandoned_subtitles
if [ ! -d "$backups" ]; then mkdir -p $backups; fi
x=0
y=0
z=0
echo
(IFS='
';
while [ $y -lt 101 ]; do
# Search for a new extenstion each time until condition is met
if [ $y -eq 0 ]; then search="*.en.srt"; fi
if [ $y -eq 1 ]; then search="*.en.smi"; fi
if [ $y -eq 2 ]; then search="*.en.sub"; fi
if [ $y -eq 3 ]; then search="*.en.idx"; fi
if [ $y -eq 4 ]; then search="*.en.forced.*"; fi
if [ $y -eq 5 ]; then search="*.ko.smi"; fi
if [ $y -eq 6 ]; then search="*.ko.srt"; fi
if [ $y -eq 7 ]; then search="*.ko.sub"; fi
if [ $y -eq 8 ]; then search="*.ko.idx"; fi
if [ $y -eq 9 ]; then search="*.srt"; z=1; fi
if [ $y -eq 10 ]; then search="*.smi"; fi
if [ $y -eq 11 ]; then search="*.sub"; fi
if [ $y -eq 12 ]; then search="*.idx"; y=100; fi
ext=`echo "$search" | sed "s/*//"`
if [ $z -eq 0 ]; then
excludeEN="RANDOMkdsjfsld7283479"
excludeKO="RANDOMEuwoieruuio1233i"
excludeFORCED="RANDOMmxnvmn9890"
else
excludeEN="*.en$ext"
excludeKO="*.ko$ext"
excludeFORCED="*.forced.*"
fi
# find the subtitle and see if there is a media file with the same basename
for i in `comm -23 <(find "$media_dir" -name "$search" ! -name "$excludeEN" ! -name "$excludeKO" ! -name "$excludeFORCED" | sed "s/$ext$//" | sort) <(find "$media_dir" -name '*.avi*' -o -name '*.mp4' -o -name '*.mkv' | sed "s/.\{4\}$//" | sort)`; do
# Count the number of subtitles found
x=$[x + 1]
echo "Found ""$i""$ext" | sed "s#"$media_dir"##"
echo "$i""$ext" >> $log
done
y=$[y + 1]
done
# ask if you want to remove the subtitles. if yes, moves them to backup directory
if [ $x -gt 0 ]; then
echo
read -p "Found "$x" abandoned subtitles. Remove these files (y/n)? " -r
if [[ $REPLY =~ ^[Yy] ]]; then
chmod +x $log
for f in $(cat $log); do
mv "$f" $backups
done
echo
echo "Moved these abandoned subtitles to $backups."
fi
else
echo "Found 0 abandoned subtitles."
fi)
echo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment