Christopher Markieta
Christopher Markieta

Reputation: 5913

Matching last occurrence before a previous match

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

Upvotes: 5

Views: 106

Answers (2)

anubhava
anubhava

Reputation: 784958

Using awk:

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

Upvotes: 4

The Guy with The Hat
The Guy with The Hat

Reputation: 11132

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

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

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

Upvotes: 0

Related Questions