Sunday, January 23, 2011

Finding and deleting files with bash

When deleting files that fit a certain criteria but are scattered all over a partition, or even across multiple partitions, it's usually a manual task. You have to search the filesystem by manually browsing through individual folders and deleting the files as you find them. For a small number of files and if you know exactly where to find them, things are still good. But if a large number of files are involved, things get tedious fast. There's also the added possibility of human error occuring. People get tired doing repetitive (and boring) work.

There's a better way to do things if there's a criteria shared in common by all (or most) of the files you want deleted: the find command.

You'll need to run find from terminal. Here's how:

~$ sudo find path -name filename -delete

Replace path with the folder you want to scan through (eg. / tells find to search for files matching pattern in the entire filesystem). pattern should be replaced with a filename that may include some wildcards (eg. * or .). Basically, you can delete groups of files that are named following a certain pattern easily.

There's more options available with the find command that can be explored with a simple command:

~$ man find

That'll bring up the manual for the find command which explains what the command does and what are the available commands for using it for your specific needs.