4

I'd like to automate cleaning up orphan subtitle files on my NAS which is serving files to KODI.

When I delete a watched tv episode in KODI, it leaves the corresponding subtitle file untouched in the directory.

I'd like to have a Bash script to recursively go through the TV folder and delete subtitle files (.srt, or sometimes .xx.srt for different language, where xx is the 2-letter language code) which do not have a corresponding .mkv, .avi or .mp4 file.

My folder structure looks like this:

-TV
  |-Show 1
  |  |-Season 01
  |  |-Season 02
  |      |-Show 1 S02E01.mkv
  |      |-Show 1 S02E01.srt
  |      |-Show 1 S02E02.avi
  |      |-Show 1 S02E02.srt
  |
  |-Show 2 
  |   |-Season 03
  |       |- Show 2 S03E02.mp4
          |- Show 2 S03E02.en.srt
          |- Show 2 S03E02.sv.srt

After deleting episodes it looks something like this:

-TV
  |-Show 1
  |  |-Season 01
  |  |-Season 02
  |      |-Show 1 S02E01.srt
  |      |-Show 1 S02E02.mp4
  |      |-Show 1 S02E02.srt
  |
  |-Show 2 
  |   |-Season 03
          |- Show 2 S03E02.en.srt
          |- Show 2 S03E02.sv.srt
5
  • You want to delete subtitles or videos? Your input and output don't really agree with each other or with the question
    – muru
    Dec 12, 2016 at 9:35
  • @muru I think the second block is not their desired output - it's showing how some of the .srt files have been orphaned?
    – Zanna
    Dec 12, 2016 at 10:26
  • @Zanna hmm, but where did that mp4 file come from?
    – muru
    Dec 12, 2016 at 10:27
  • @muru haha good question!
    – Zanna
    Dec 12, 2016 at 10:27
  • 2
    Instead of writing Solved in the question's title, please mark the answer that solved your problem by clicking the check mark below the answer's score.
    – Dan
    Dec 12, 2016 at 11:04

1 Answer 1

6

You can use a for loop and some tests

for f in Show*/Season*/*.srt; do if [[ ! -f "${f%%.*}.mkv" ]] && [[ ! -f "${f%%.*}.mp4" ]] && [[ ! -f "${f%%.*}.avi" ]]; then echo rm -v -- "$f"; fi; done

Remove echo after testing to delete the files

As a script:

#!/bin/bash
for f in Show*/Season*/*.srt; do
    if [[ ! -f "${f%%.*}.mkv" ]] &&
       [[ ! -f "${f%%.*}.mp4" ]] &&
       [[ ! -f "${f%%.*}.avi" ]]; then
         echo rm -v -- "$f"
    fi
done

And remove echo to really do the job, if you see it is going to remove the correct files...

if [[ ! -f "${f%%.*}.mkv" ]]; then means, if there is no such file as the file we are dealing with, that has an .mkv extension instead of .srt, then do something with the current file.

3
  • if [[ ! -f "${f%%.*}.mkv" ]] && [[ ! -f "${f%%.*}.mp4" ]] && ...
    – muru
    Dec 12, 2016 at 10:28
  • Great! Works as a charm!
    – ICDeadPpl
    Dec 12, 2016 at 10:49
  • @ICDeadPpl it's great to hear that :)
    – Zanna
    Dec 12, 2016 at 10:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.