How to detect files with the same name but different extensions?
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
.)
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.