April 22, 2015

Unix find tip: Excluding files

Sometimes you want to find files on a Unix file system but exclude files either by specific name or by pattern.  The best way I found to do this is by using a combination of find and grep.  Let's take a look.

$ find . -type f | grep -P '^(.(?!Thumbs\.db))*$'

This example uses the find command in the current directory (.) and limits the search to just files (-type f) instead of both files and directories. The result is then piped to grep. The regular expression (-P '^(.(?!Thumbs\.db))*$')  filters out all results from the find command that end with Thumbs.db.

So this is a quick and easy way to exclud files by a specific name.  Next let's take a look at how to exclude files by pattern.

find . -type f | grep -P '^(.(?!\.ffs_db))*$'

This example uses a little more complicated regular expression (-P '^(.(?!\.ffs_db))*$') to filter all results from the find command that end with .ffs_db. This example is essentially exclude by file name extension.

Now what if you want to exclude multiple file names or file types?  Just pipe together more grep statements.

find . -type f | grep -P '^(.(?!Thumbs\.db))*$' | grep -P '^(.(?!\.ffs_db))*$' | grep -P '^(.(?!\.ffs_gui))*$'

In this final example, I am excluding files named Thumbs.db, files that end with .ffs_db and files that end with .ffs_gui.

References
Retrieved April 13, 2015 from http://fineonly.com/solutions/regex-exclude-a-string

Enjoy!