Find files that don’t contain certain text patterns

4 02 2010

Today I had to find a list of files that didn’t contain a particular piece of text.  At first I thought this would be relatively straightforward but a few attempts and googles yielded no success.  I tried to grep using the ‘-v’ option but this will return all the lines that don’t match the pattern in all files.  After dabbling with a for loop in which I grep’d each file individually, then noted which greps failed (by checking the exit status of grep $?) I asked a colleague.  We eventually found a one-liner that did what we needed:

find <directory_name> -name <file_name_pattern> -type f ! -exec grep -q <string_pattern> {} ‘;’ -print

Key to this was the ‘!’ which inverted the grep execution.  In my case I had to find out which ethernet interfaces where ‘not’ members of bond0, so I ended up with:

find /etc/sysconfig/network-scripts/ -name “ifcfg-eth*” -type f ! -exec grep -q “MASTER=bond0” ‘;’ -print

This printed a list of all the ifcfg-eth* files in /etc/sysconfig/network-scripts/ which do ‘not’ contain the line ‘MASTER=bond0’.




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: