Matching last occurrence before a previous match

awk, bash, grep, regex

Solution

Using awk:

awk -v s='2' '/^foo:/{line=$0;next} $1==s{print line}' file
foo: A
foo: C

Problem

How do I match the last occurrence of `foo` before the match of some number? ``` foo: A 1 2 foo: B 1 foo: C 2 ``` A search for pattern `2` should return: ``` foo: A foo: C ```

Original source