Bash Scripting – Delete Files with Same Name but Different Extensions

bashfilenamesrm

I have a mess in my photo libary. I have files like these:

image-1.jpg 
image-1.jpeg
image-2.jpg

Now I want to delete all photos with the extension .jpeg when there is a file with the same name but with the extension .jpg.

How can I do this?

Best Answer

for f in *.jpeg; do
  [ -e "${f%.*}.jpg" ] && echo rm -- "$f"
done

(remove echo if happy).

With zsh and one rm invocation:

echo rm -- *.jpeg(e'{[ -e $REPLY:r.jpg ]}')

(change * to **/* to do that recursively, add the D glob qualifier, if you also want to consider hidden files or files in hidden directories).

Related Question