Posted in Linux commands

“find” with Style, Part 2: Deleting Files

Now let’s delete files with style. The usual command to clean up a directory tree (e.g. to delete .o files) is

$ find . -name '*.o' -exec rm {} \;

As I wrote in an earlier post this calls rm for every single file. A first improvement is to change the terminator at the end of the line:

$ find . -name '*.o' -exec rm {} +

This collects the file names until the maximum command line length is reached, and results in much fewer calls to rm.

But why not letting find do the work itself? find has a parameter to delete files:

$ find . -name '*.o' -delete

This time no system call is necessary, and you get an even quicker removal.

Want to know what you’ve deleted? Just add the -print parameter:

$ find . -name '*.o' -delete -print

You can see the list of deleted files (and start a panic while watching what has gone, if you accidentally used the wrong file pattern).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s