Delete all files to which no corresponding file with another extension exists

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…

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply