Deleting files using find

We will learn how to delete files using command find from given folder.

Suppose you want to delete .png files from /home/directory.

Use following command

find /home/directory/ \( -name "*.png" \) -type f -exec rm {} +

This will delete file with extension .png from /home/directory and sub directories of /home/directory like *.png files from /home/directory/directory2/ as well .

But suppose if you need to delete .png files only from directory /home/directory and not from sub directories then use following command.

find /home/directory/ -maxdepth 1  \( -name "*.png" \) -type f -exec rm {} +

command to delete empty folders on linux

Sometime we need to find remove only those folders which are empty. (Doesn’t contains any file or folder) .  rmdir is command which will delete folder only if it is empty.

find . -type d -exec rmdir {} \;
This command will find all files with type d (type d means all files those are directories) in present folder. Then execute rmdir for all directories but since rmdir will remove only empty folder and for other it will throw error.