kd4ttc
kd4ttc

Reputation: 1205

Ever try to delete files with unix shell find? Use the -delete option

This has come up a number of times in posts, so I'm mentioning it as a thankyou to all helpful people on stackoverflow.

Have you ever wanted to do a bunch of deletes from the command line/terminal in Unix? Perhaps you used a construct like

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

Look to the answer for an elegant way to do this.

Upvotes: 8

Views: 7570

Answers (2)

kd4ttc
kd4ttc

Reputation: 1205

Here's how to do it with the -delete option!

Use the find command option -delete:

find . -name '*.pyc' -delete

Of course, do try a dry run without the -delete, to see if you are going to delete what you want!!! Those computers do run so darn fast! ;-)

Upvotes: 21

Tim Pote
Tim Pote

Reputation: 28049

+1 for taking the initiative and finding the solution to your issue yourself. A couple of rather minor notes:

I would recommend getting into the habit of using the -type f flag when you're wanting to delete files. This restricts find to files that are actually files (i.e. not directories or links). Otherwise you might inadvertently delete a directory, which is probably not what you wanted to do. (That said, unless you have a directory named 'something.pyc', that wouldn't be an issue for your example command. It's just a good habit in general.)

Also, just to let you know, if you decide use the -exec rm.. version, it would run faster if you did this instead:

find . -type f -name '*.pyc' -exec rm {} \+

This version adds as many arguments to a single invokation of rm as it can, thereby reducing the total number of calls to rm. It works pretty much like the default behavior in xargs.

Upvotes: 6

Related Questions