grep – find files, which have no match in their entire content

Here is a quick tip for a very useful option, which is not widely known!
If you want to search for a matching string in a file you can use “grep” to look for lines in the file with the matching string, but what if you would like to search for files, which DO NOT contain the search string?
The Unix-world command grep has the option “-L”, which will output the name of the file not containing the search string:

-L, –files-without-match – Suppress normal output; instead print the name of each input file from which no output would normally have been printed. The scanning will stop on the first match.

The quote is from grep’s man page!
Some simple examples:

myuser@srv:~/tmp$ grep -L DISTRIB_DESCRIPTION *
10.10.10.10
10.10.10.11
10.10.10.12
10.10.10.13
10.10.10.50
myuser@srv:~/tmp$ grep DISTRIB_DESCRIPTION *
10.10.10.14:DISTRIB_DESCRIPTION="Ubuntu 16.04.5 LTS"
10.10.10.15:DISTRIB_DESCRIPTION="Ubuntu 16.04.5 LTS"
10.10.10.16:DISTRIB_DESCRIPTION="Ubuntu 16.04.5 LTS"
10.10.10.17:DISTRIB_DESCRIPTION="Ubuntu 16.04.5 LTS"
10.10.10.18:DISTRIB_DESCRIPTION="Ubuntu 16.04.5 LTS"
10.10.10.19:DISTRIB_DESCRIPTION="Ubuntu 16.04.5 LTS"
10.10.10.20:DISTRIB_DESCRIPTION="Ubuntu 16.04.5 LTS"
10.10.10.51:DISTRIB_DESCRIPTION="Ubuntu 16.04.5 LTS"
10.10.10.52:DISTRIB_DESCRIPTION="Ubuntu 16.04.5 LTS"
10.10.10.53:DISTRIB_DESCRIPTION="Ubuntu 16.04.5 LTS"

As you can see including the “-L” option will output only names, because no match is found in the files. And if you miss the option the output will show you all files and lines in the files matching the search string.
In addition, if you use “-l” (note this time the letter “l” is lower case), you the searching in the file stops on the first match, so searching in multiple files the output will include only one time the name and the match of a file on contrast when not using “-l” will output the same files’ names with the match the times matched:

myuser@srv:~/tmp$ grep VERSION *
10.10.10.14:VERSION="16.04.5 LTS (Xenial Xerus)"
10.10.10.14:VERSION_ID="16.04"
10.10.10.14:VERSION_CODENAME=xenial
10.10.10.15:VERSION="16.04.5 LTS (Xenial Xerus)"
10.10.10.15:VERSION_ID="16.04"
10.10.10.15:VERSION_CODENAME=xenial
10.10.10.16:VERSION="16.04.5 LTS (Xenial Xerus)"
10.10.10.16:VERSION_ID="16.04"
10.10.10.16:VERSION_CODENAME=xenial
myuser@srv:~/tmp$ grep -l VERSION *
10.10.10.14
10.10.10.15
10.10.10.16

Leave a Reply

Your email address will not be published.