Remove all files that does not have the following extensions in Linux

Tike picture Tike · Dec 27, 2011 · Viewed 19.6k times · Source

I have a list of extensions:

avi,mkv,wmv,mp4,mp5,flv,M4V,mpeg,mov,m1v,m2v,3gp,avchd

I want to remove all files without the following extensions aswell as files without extension in a directory in linux.

How can I do this using the rm linux command?

Answer

jaypal singh picture jaypal singh · Dec 27, 2011

You will first have to find out files that do not contain those extension. You can do this very easily with the find command. You can build on the following command -

find /path/to/files ! -name "*.avi" -type f -exec rm -i {} \;

You can also use -regex instead of -name to feed in complex search pattern. ! is to negate the search. So it will effectively list out those files that do not contain those extensions.

It is good to do rm -i as it will list out all the files before deleting. It may become tedious if your list is comprehensive so you can decide yourself to include it or not.

Deleting tons of files using this can be dangerous. Once deleted you can never get them back. So make sure you run the find command without the rm first to inspect the list throughly before deleting them.

Update:

As stated in the comments by aculich, you can also do the following -

find /path/to/files ! -name "*.avi" -type f -delete

-type f will ensure that it will only find and delete regular files and will not touch any directories, sym links etc.