Take a look at the --max-count
option:
tail -f file.log | grep -m 1 'PATTERN'
It will exit after the first line that matches PATTERN
.
EDIT: take note of @Karoly's comment below. If the file.log
velocity is slow, it's possible that the grep
process will block until additional content is added to the file after the matching line.
echo 'context PATTERN line' >> file.log ## grep shows the match but doesn't exit
will print the matching line, but it will not exit until additional content is appended to the file (even if it doesn't have a newline yet):
echo -n ' ' >> file.log ## Now the grep process exits
In some cases (such as a high-velocity log file), this isn't a big deal, because new content is probably going to be added to the file soon anyway.
Also note that this behavior does not happen when reading from a console as stdin, so it appears to be a difference in the way grep
reads from a pipe:
$ grep -m1 'PATTERN' - # manually type PATTERN and enter, exits immediately
$ cat | grep -m1 'PATTERN' # manually type PATTERN and enter, and it hangs
-q
isn't portable, it is specified by POSIX. – Militarism