An approach I would like to take to undo the problem, since it is easier to find the first match and print the context lines. Take the file:
$ cat file foo 1 2 foo 3 4 foo 5 6
Let's say we want the last match foo and the next one in lines we can just cancel the file with tac , find the first match and n lines above using -Bn and stop using -m1 . Then just flip the output with tac:
$ tac file | grep foo -B2 -m1 | tac foo 5 6
Tools like tac and rev can create problems that seem complicated a lot easier.
source share