Regex back find all text between line and first occurrence of another line

I need to find the most recent occurrence of “GET” (GET zzzz) before “error:” and capture all the text between them.

GET xxxxx
GET yyyyy
GET zzzzz
Some text
more text
error: this is an error

Can this be done?

change

Thank you, awk solution works, but can it be further improved by getting LAST error:?

GET xxxxx
GET yyyyy
GET zzzzz
Some text
more text
error: this is the first error

GET xxxxx
GET yyyyy
GET zzzzz
Some text
more text
error: this is the last error
+4
source share
3 answers

Try the following awksolution:

awk '
  /^GET/ { delete lines; c=0; inBlock=1 }
  /^error:/ { for(i=1; i<=c; ++i) print lines[i]; print; exit }
  inBlock { lines[++c] = $0 }
' file

This assumes that only 1 block should be printed and that a line should also be printed error:. (Update: see below for a solution that prints only the last block).

  • /^GET/ { delete lines; c=0; inBlock=1 } lines , GET .
  • /^error:/ { for(i=1; i<=c; ++i) print lines[i]; print; exit } error: , , , .
  • inBlock { lines[++c] = $0 } , GET .

, OP:

() , error:, :

awk '
  /^GET/ { delete lines; c=0; inBlock=1 }
  inBlock { lines[++c] = $0 }
  /^error:/ { inBlock=0; }
  END { for(i=1; i<=c; ++i) print lines[i] }
' file

, , "", , END Awk script.

+3

:

$ echo "$tgt"
first line
second line
GET xxxxx
GET yyyyy
GET zzzzz
Some text
more text
error: this is the first error

GET xxxxx
GET yyyyy
GET zzzzzLAST
Some text
more text
error: this is the last error
last line

, :

/^.*^(GET.*^error[^\n]*)/ms

Perl . -0777 :

$ echo "$tgt" | perl -0777 -ne 'print $1 if m/^.*^(GET.*^error[^\n]*)/sm'
GET zzzzzLAST
Some text
more text
error: this is the last error

"", :

/\A.*^(GET.*^error.*)\Z/ms

Perl:

$ echo "$tgt" | perl -0777 -ne 'print $1 if m/\A.*^(GET.*^error.*)\Z/ms'
GET zzzzzLAST
Some text
more text
error: this is the last error
last line
+1

I managed to get the desired result using the following regexp:

(GET[^\n]+\n(?!GET).*)error:

You can check it at http://regexpal.com/ in ". Matches all" modes.

-1
source

All Articles