Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have the following command that lists all files with the extension doc, docx, etc.

find . -maxdepth 1 -iname \*.doc\*

The command returns numerous files some of which I would like to delete. So for example the results returned are

  1. Example.docx
  2. Dummydata.doc
  3. Sample.doc

I would like to delete Sample.doc and Dummydata.docx. How do I delete the files using the -exec option. Am I able to pass in the names of the files e.g. rm Dummydata.docx Sample.doc hence the command would look as follows

find . -maxdepth 1 -iname \*.doc\* -exec rm Dummydata.docx Sample.doc

Can I pass the names of the files within {} afterrm`? e.g.

find . -maxdepth 1 -iname \*.doc\* -exec rm {Dummydata.docx} Sample.doc

Is there a better way of doing it?

share|improve this question
up vote 1 down vote accepted

If you know the names of the files in advance, it'd be easier to just remove them right away:

find . -iname "Dummydata.doc" -delete

Or, with multiple conditions:

find . \( -iname "Dummydata.doc" -o -iname "Sample.doc" \)

The parentheses force preference, but you need to escape or quote them since usually, parentheses have a special meaning to your shell.

Otherwise if you want to examine the list of results first, you can pass the path of the found files – here, put into {} – to sh. For the sh command, the path will become $0, and you can compare it with the name of the file you want to remove:

find . -maxdepth 1 -iname "*.doc" \
-exec sh -c 'if [ "$0" == "Dummydata.doc" ] || [ "$0" == "Sample.doc" ]; then echo rm "$0"; fi' {} \;

Here, remove echo once you're sure the correct file will be removed. But I'm afraid it will be easier to just manually remove the files.

share|improve this answer
Passing it to sh still assumes I know the name of the file or files doesn't it? – PeanutsMonkey Sep 22 '12 at 8:49
Of course. But do you know the names of the files you want to remove in advance or not? That aspect wasn't too clear in your question, because if you knew, you could have removed them right away :) – slhck Sep 22 '12 at 8:49
Sorry. I did not know the names in advance. – PeanutsMonkey Sep 22 '12 at 8:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .