shellrar

Shell script for finding (and deleting) video files if they came from a rar


My download program automatically unrars rar archives, which is all well and good as Sonarr and Radarr need that original video file to import. But now my download HDD fills up with all these video files I no longer need.

I've tried playing around with modifying existing scripts I have, but every step seems to take me further from the goal.

Here's what I have so far (that isnt working and I clearly dont know what im doing). My main problem is I can't get it to find the files correctly yet. This script jumps right to "no files found". So I'm doing the search wrong at the very least. Or I'm pretty sure I might need to completely rewrite from scratch using a different method I'm not aware of..

#!/bin/bash
# Find video files and if it came from a rar, remove it. 

# If no directory is given, work in local dir
if [ "$1" = "" ]; then
  DIR="."
else
  DIR="$1"
fi

# Find all the MKV files in this dir and its subdirs
find "$DIR" -type f -name '*.mkv' | while read filename

do

# If video file and rar file exists, delete mkv.

for f in ...
do
    if [[ -f "$DIR/*.mkv" ]] && [[ -f "$DIR/*.rar" ]]
    then
#   rm $filename
    printf "[Dry run delete]: $filename\n"
    else
    printf "No files found\n"
    exit 1
fi
done

Example of directory structure before and after. Note the file names are often different to the extracted file. And I want to leave other folders that don't have rars in them alone.

Before:

/folder/moviename/Movie.that.came.from.rar.2021.dvdrip.mkv
/folder/moviename/movie.rar
/folder/moviename/movie.r00
/folder/moviename/movie.r01

/folder/moviename2/Movie.that.lives.alone.2021.dvdrip.mkv
/folder/moviename2/Movie.2021.dvdrip.nfo

After

# (deleted the mkv only from the first folder)
/folder/moviename/movie.rar
/folder/moviename/movie.r00
/folder/moviename/movie.r01

# (this mkv survives)
/folder/moviename2/Movie.that.lives.alone.2021.dvdrip.mkv
/folder/moviename2/Movie.2021.dvdrip.nfo

TL:DR I would like a script to look recursively in my download drive for video files and rar files, and if it sees both in the same folder, delete the video file.


Solution

  • With GNU find, you can condense this to one command:

    find "${1:-.}" -type f -name '*.rar' -execdir sh -c 'echo rm *.mkv' \;
    

    ${1:-.} says "use $1, or . if $1 is undefined or empty".

    For each .rar file found, this starts a new shell in the directory of the file found (that's what -execdir sh -c '...' does) and runs echo rm *.mkv.

    If the list of files to delete looks correct, you can actually delete them by dropping the echo:

    find "${1:-.}" -type f -name '*.rar' -execdir sh -c 'rm *.mkv' \;
    

    Two remarks, though: