6

I have a directory whose files have extension either .JPG or .NEF and I want to delete the files of the form X.NEF for which X.JPG does not exist in the directory. (X here can be any string.) I don't know how to do this other than by hand.

A more general situation is when you want to find all the files in a directory A which exist in directory B as well. (The first problem can be turned into the second one using mmv.)

8

You can use the shell's ${var%ext} parameter substitution features to remove the original extension on a per-file basis: to illustrate

touch file{1..6}.NEF file{1,2,4,6}.JPG

Then

for nef in *.NEF; do [[ -f "${nef%.NEF}.JPG" ]] || echo rm -- "$nef"; done

results in

rm -- file3.NEF
rm -- file5.NEF

Explanation:

The first command just creates 6 .NEF files numbered file1.NEF to file6.NEF and corresponding .JPG files for 3 of them i.e. just some empty files to test the second command on.

  • @terdon Ooops I just realize I "stole" your more compact version in my edit. BTW is -e or -f preferred for the test here in your opinion? – steeldriver Jun 12 '15 at 12:10
  • Could you explain what the first command does? – Reza Jun 12 '15 at 12:19
  • @steeldriver I think -f is better since it doesn't consider directories as valid hits. I just found out it does accept symlinks (despite claiming to be about "regular" files) which was my reason for using -e instead. And "steal" away, it's not like it's a form you hadn't seen before :) – terdon Jun 12 '15 at 13:04
  • @Reza the first command just creates 6 .NEF files numbered file1.NEF to file6.NEF and corresponding .JPG files for 3 of them i.e. just some empty files to test the second command on – steeldriver Jun 12 '15 at 13:06
  • @steeldriver I moved your explanation into your answer - maybe you'd like to explain the rest of your fine commands too? – guntbert Jul 2 '15 at 17:24

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.