Grep - limit the number of read files

I have a directory with over 100,000 files. I want to know if the string "str1" exists as part of the contents of any of these files.

Command: grep -l 'str1' * takes too much time while reading all files.

How can I ask grep to stop reading any further files if it finds a match? Any one line?

Note. I tried grep -l 'str1' * | head grep -l 'str1' * | head , but the command takes as much time as the previous one.

+7
linux bash grep
source share
2 answers

Naming 100,000 file names in your args command will cause a problem. This is likely to exceed the size of the shell command line.

But you do not need to specify all the files if you use the recursive option only with the name of the directory in which the files are located (which is located . If you want to search for files in the current directory):

 grep -l -r 'str1' . | head -1 
+5
source share

Use grep -m 1 to grep stop after searching for the first match in the file. It is extremely effective for large text files.

 grep -m 1 str1 * /dev/null | head -1 

If there is one file, then / dev / null above ensures that grep prints the file name in the output.

If you want to stop after searching for the first match in any file:

 for file in *; do if grep -q -m 1 str1 "$file"; then echo "$file" break fi done 

The for loop also eliminates the problem of too many arguments when you have a directory with many files.

+3
source share

All Articles