How to Find All Files Not Containing Specific Text on Linux

How to find all files that do not contain a specific text in Linux command line?

There could be a number of ways to find files not containing specific text in Linux command line. My favorite way is to use Grep command here.

This is similar to what I did for finding all files containing specific text. You can use the same grep command with option ‘L’ instead of ‘l’ to achieve this.

grep -RiL "specific_text" <search_directory>
  • R option search recursively in subdirectories and in symbolic links
  • i option is for case-insensitive search
  • L option will print only the name of the files that do not contain the specific text

This will help you find all the files that do not contain the specified string in the given directory and its subdirectories.

Let me show this with an example.

List all files not containing text

I have the following files and sub-directories:

-rw-r--r-- 1 abhishek abhishek 12817 Sep 22 12:28 file1.txt
-rwxrw-r-- 1 abhishek abhishek 12813 Sep 22 12:29 file2.txt
-rw-r--r-- 1 abhishek abhishek 12817 Sep 22 12:29 file3.txt
-rw-rw-r-- 1 abhishek abhishek   311 Sep 22 12:19 line.txt
drwxrwxr-x 2 abhishek abhishek  4096 Aug 22 16:58 new
drwxrwxr-x 2 abhishek abhishek  4096 Aug 22 17:02 old
-rw-r--r-- 1 abhishek abhishek 12817 Sep 22 12:28 sample.txt

And I want to list all the files that do not contain the string LHB.

grep -RiL LHB .

Here's the result I got.

./line.txt
./old/gnome-console-voiceover
./file2.txt
./.some_config
./new/my_file.txt

As you can see, it showed all the non-matching files in the current directory as well as from the sub-directories.

Don't go into subdirectories

What if you want to search only in the current directory, not the sub-directories?

You can specify * instead of . and remove the recursive option of Grep.

grep -iL LHB *

With *, it searches into all files in the current directory. Here's the output now.

abhishek@itsfoss:~/test$ grep -iL LHB *
file2.txt
line.txt
grep: new: Is a directory
new
grep: old: Is a directory
old

The error message is because grep can work directly only on the file names, not directory names. You can skip the directories like this:

grep -iL -d skip LHB *

This gives a cleaner output:

abhishek@itsfoss:~/test$ grep -iL -d skip LHB *
file2.txt
line.txt

If you want to search only in files matching a certain pattern, you can combine grep with find exec commands:

find . -iname "*.txt" -exec grep -Li "mystring" {} \+

Do you use some other way to find all files not matching the string in Linux? Do share it with us in the comment section.