Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. 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

There are hundreds of .html files in a directory. I need to delete files that don't contain word bluecar in their contents.

I thought sed with rm would do that, but I don't know how to combine them.

share|improve this question
up vote 4 down vote accepted

This should work using grep:

grep -L bluecar *.html | xargs rm
share|improve this answer
This not work for files with spaces in names. – php-coder May 17 '11 at 4:23
Thanks for the tip – Chris J May 19 '11 at 2:08
This is easily fixed to work with filenames with spaces, at least with GNU tools: grep -ZL bluecar *.html | xargs -0 rm. I'd edit it in, but I see @php-coder already put in an answer with this... – derobert Nov 28 '12 at 17:03
won't this remove those that do contain bluecar? – amphibient Mar 12 '13 at 20:53
@amphibient -L is --files-without-match – Chris J Mar 12 '13 at 22:55

With GNU grep/xargs you may use

grep -LZ -- str *.html | xargs -r0 rm
share|improve this answer

The find tool is the usual one to use.

find . -name "*.html" \( -exec grep -q bluecar {} \; -o -exec rm {} \; \)


find . -name "*.html" ! -exec grep -q bluecar {} \; -exec rm {} \;

But try it on a copy first...

share|improve this answer
Does this really take only arguments that returned a success code from the first exec and run them in the second or does it just run the full argument list through both execs? – Caleb May 17 '11 at 9:54
@Caleb: Yes, -exec is true iff the command returns 0, and the find boolean operators short-circuit. – Gilles May 17 '11 at 11:40
@gilles Thanks for fixing that. – Keith May 17 '11 at 19:55
Is there some reason to use -exec rm … instead of -delete? -delete is generally much more efficient (saves a fork/exec per file). – derobert Nov 28 '12 at 17:05
@derobert No reason other than I'm not sure older versions of find have that action, and my habit of just using exec. – Keith Nov 28 '12 at 18:16

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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