Search code examples
bashfile-extension

How to delete JPG files, but only if the matching RAW file exists?


On debian terminal, I try to delete all .jpg of a folder and subfolder if .cr2 exist on the same folder.

Assumes they have the same name. 123.jpg 123.cr2

I know how to delete all .jpg with find command.

find {PATH} -type f -name '*.jpg' -delete

but how can I add a condition (if .cr2 exist)

I found this 10y topics but it's for windows and python


Solution

  • You can try something like:

    shopt -s globstar
    for i in /path/**.jpg
    do
    RAW=${i%.jpg}.cr2
    if [ -f "$RAW" ]
    then rm "$i"
    fi
    done
    

    If you are fan of oneliners you can convert the script to something like:

    shopt -s globstar; for i in /path/**.jpg; do [ -f "${i%.jpg}.cr2" ] && rm "$i"; done