(exec <file.txt; grep -m 85 'PATTERN' | tail -n 1; head -n 5)
Obviously you can adjust the numbers as desired.
From man grep
:
-m NUM, --max-count=NUM
Stop reading a file after NUM matching lines. If the input is
standard input from a regular file, and NUM matching lines are
output, grep ensures that the standard input is positioned to
just after the last matching line before exiting, regardless of
the presence of trailing context lines. This enables a calling
process to resume a search.
The above command takes advantage of this feature by using a subshell and setting the STDIN to the file that you intend to grep
, so that this feature can work correctly. Then you can simply catch the final (85th) instance with tail -n 1
, and get the context lines you want with a separate call to head
.
Use this command if you know that the file has at least 85 instances of PATTERN
; in that case it will work perfectly.
If it may have less, the command will require some adjustment; in its current state it will simply print the final match with no trailing context lines if there are fewer matches than you've requested.