Delete Files Without Corresponding Extension – Shell Script Guide

filesshellwildcards

My goal is to find a Linux command sequence, which deletes some files if a special condition is fulfilled:

All files with the extensions .cut or .cut.bak in the current directory shall be removed, IF there is no file having the same name, but extension .rec or .mpg in the current directory.

Background: I am developing a tool for a Linux-based PVR, that allows cutting of recorded programs. For each recording (extension .rec or .mpg) the segment markers are stored in a .cut-file with the same name. When some recording gets moved/renamed/deleted, then the corresponding cut-file remains orphaned and shall be deleted. I already have implemented the removing of those useless cut-files in C. But I am wondering, whether there may be a (simple) system based solution. In this case it could be run via 'system' and & in the background, which would make my application more responsive…

I already asked a similar question for the recursive case (browsing also into subdirectories), here.
There has been a (nearly) perfect answer by kos – but unfortunately it removes too many files, so it is not usable, and I was not able to figure it out…
But the same idea can be used here, IF it is possible to parse and pipe the result of 'ls' linewise…

Best Answer

Like this?

for f in *.cut *.cut.bak
do
    [ -e "$f" ] || continue
    f="${f%%.bak}"
    f="${f%%.cut}"
    [ -e "$f".mpg ] || [ -e "$f".rec ] || rm -i -- "$f".cut "$f".cut.bak
done