How to Delete Files by Extension in a Linux/Unix Shell?

In Linux (or Unix), to delete all files by an extension name, you can use the rm command, for example, like so:

rm *.pdf

In the example above, the wildcard (*) together with the file extension indicates that all filenames should be deleted that have a ".pdf" file extension.

You could also partially provide the filename that starts-with, ends-with or contains a particular word:

rm foo*.pdf # remove all "pdf" files that start with "foo"
rm *foo.pdf # remove all "pdf" files that end with "foo"
rm *foo*.pdf # remove all "pdf" files that contain "foo"

To add more utility to file deletion via the rm command, you can use one or more of the following flags:

-i # confirm before deleting each file
-f # remove without confirmation, regardless of the file's permissions
-v # be verbose (i.e. show files as they're removed)

If -f and -i flags are used together then the -f option overrides the -i option.

For example, if you would like to be asked for confirmation before deletion of each file, then you could use the -i flag, like so:

rm -i *.pdf

If you would like the files to be removed without confirmation (regardless of the file's permissions), whilst showing the file names as they're deleted, then you could use -f and -v together, for example, like so:

rm -fv *.pdf

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.