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 {} \;

Tagged with: , , , ,
Posted in The Linux and Unix Articles!

Leave a Reply

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




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