Delete all the files not matching pattern with find and grep

In this article I will show you how to remove all the files that do not match a certain pattern, with grep and find, combined with grep:

As an example, I will remove all the files not containing the string foo, with the .txt extension:

With grep:

$ grep -ZL foo *.txt | xargs -0 rm

With find + grep:

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

Share and Enjoy

  • Twitter
  • Facebook
  • Google Plus
  • Email
  • RSS
Tagged with: , , , ,
Posted in The Linux and Unix Articles!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe

  

Subscribe to get the latest Linux news and how to guides directly on your e-mail!