2

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...

  • Don't parse ls, use globbing... – jasonwryan Jul 7 '15 at 21:50
  • I don't know what 'globbing' means. But parsing ls should be fine, because newlines in filenames are not allowed on the PVR! – chris86 Jul 7 '15 at 21:55
  • Globbing is explained in the link. – jasonwryan Jul 7 '15 at 21:57
  • That's a good idea! So I would start off with the following loop: for f in *.cut *.cut.bak; do [[ -e $f ]] || continue echo $f done But I don't know how to formulate the condition (with 'sed'?) to check the existance of the needed files. – chris86 Jul 7 '15 at 22:31
  • 1
    I would read all the files into an array and then iterate over them checking to see if, for each file, there are the requisite extensions. You should edit your question and title to capture your generic issue, as opposed to how you think it should be solved: you will attract more attention. – jasonwryan Jul 7 '15 at 22:39
2

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
  • Very good approach, thanks! But, when I run this (replaced 'rm' by 'echo' for testing) it very often returns one line "-i -- *.cut *.cut.bak", which removes just everything! What can that be? – chris86 Jul 8 '15 at 14:35
  • Compare: echo * vs. echo "*". So it just means there was no *.cut or *.cut.bak. But I added a line that should prevent this case. – frostschutz Jul 8 '15 at 14:44

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.