Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching last occurrence before a previous match

Tags:

regex

grep

bash

awk

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
like image 678
Christopher Markieta Avatar asked Oct 01 '22 16:10

Christopher Markieta


1 Answers

Using awk:

awk -v s='2' '/^foo:/{line=$0;next} $1==s{print line}' file
foo: A
foo: C
like image 169
anubhava Avatar answered Oct 12 '22 10:10

anubhava