Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
add comment

3 Answers 3

up vote 4 down vote accepted

This should work using grep:

grep -L bluecar *.html | xargs rm
share|improve this answer
3  
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
1  
@amphibient -L is --files-without-match –  Chris J Mar 12 '13 at 22:55
add comment

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

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
add comment

With GNU grep/xargs you may use

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

Your Answer

 
discard

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.