How to stop grep at first match


#1

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?


#2

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

#3

Yes, you can follow what sputnik informed you.