Tuesday, January 30, 2024

[SOLVED] How to loop through a directory recursively to delete files with certain extensions

Issue

I need to loop through a directory recursively and remove all files with extension .pdf and .doc. I'm managing to loop through a directory recursively but not managing to filter the files with the above mentioned file extensions.

My code so far

#/bin/sh

SEARCH_FOLDER="/tmp/*"

for f in $SEARCH_FOLDER
do
    if [ -d "$f" ]
    then
        for ff in $f/*
        do      
            echo "Processing $ff"
        done
    else
        echo "Processing file $f"
    fi
done

I need help to complete the code, since I'm not getting anywhere.


Solution

find is just made for that.

find /tmp -name '*.pdf' -or -name '*.doc' | xargs rm


Answered By - mouviciel
Answer Checked By - David Goodson (WPSolving Volunteer)