5

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
Christopher Markieta
  • 5,674
  • 10
  • 43
  • 60

2 Answers2

4

Using awk:

awk -v s='2' '/^foo:/{line=$0;next} $1==s{print line}' file
foo: A
foo: C
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

This regex could definitely use some optimization, but it should work:

foo: [A-Z](?=(?:(?!foo)[^2])*2)

Demonstration: http://regex101.com/r/cX8gM0

The Guy with The Hat
  • 10,836
  • 8
  • 57
  • 75