8

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.

5
  • 1
    You should separate this into a question and an answer.
    – SLaks
    Jun 6, 2012 at 22:23
  • 1
    Also, please add that a dry run is necessary. find can find stuff you didn't know you had. Jun 6, 2012 at 22:26
  • Not only do users here answer questions, they help newbies get better at using the site! Thanks, gnetlemen! I have edited the original post after looking at the reference made by @SLaks
    – kd4ttc
    Jun 6, 2012 at 22:33
  • You're welcome! See also meta.stackoverflow.com
    – SLaks
    Jun 6, 2012 at 22:38

2 Answers 2

21

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! ;-)

1
  • 1
    If you do a dry run without the -delete flag, when you're ready to delete, make sure you add the flag to the end! Otherwise, the filter flags that come after it may be ignored.
    – Michael
    Feb 26, 2015 at 15:24
6

+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.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.