How to stop grep at first match


I have very big text files (more than 4 GB in size) and I know that my search pattern occurs at most one time in that file.

I’m writing a script to find patterns in that file but even if the grep finds the pattern at the very beginning of the file, it is continue to search until end of the file.

I don’t want to wait until end of the file in my script because I know that there can be only one match at most.

So, how can I tell grep to stop finding another matching lines after a matched line was found?


You can use -m option, see the descriptions from manpage below:

-m NUM, --max-count=NUM
    Stop reading a file after NUM matching lines.

If you know that there will be only one matching, you should use the grep like that:

$ grep -m 1 pattern file.txt


Yes, you can follow what sputnik informed you.