3

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.

4

This should work using grep:

grep -L bluecar *.html | xargs rm
  • 3
    This not work for files with spaces in names. – php-coder May 17 '11 at 4:23
  • 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
  • 1
    @amphibient -L is --files-without-match – Chris J Mar 12 '13 at 22:55
5

With GNU grep/xargs you may use

grep -LZ -- str *.html | xargs -r0 rm
4

The find tool is the usual one to use.

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

or

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

But try it on a copy first...

  • 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
  • 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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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