Grep and fetch subsequent lines also

Hi, I need to grep a pattern and fetch subsequent lines till end of the data-set.

E.g., i have a file like:

AA 1111 23 34
BB 45 56 78
CC 22 44
AA 2222 78 34 56
BB 22 56 67 68 23
CC 56 78
DD 33 55 77
AA 3333 46
BB 58 79

In above file i have 3-data sets where each set starts with "AA".

if i grep for "2222" then i should get the below output (4 lines):

AA 2222 78 34 56
BB 22 56 67 68 23
CC 56 78
DD 33 55 77.

Likewise if i grep for "1111" then output should be as below:
AA 1111 23 34
BB 45 56 78
CC 22 44

Pl advise.
TIA
prvn

grep is not the right tool to use.

$ awk 'BEGIN{ toget="2222" ;}$1=="AA"{g=0}$1=="AA" && $2==toget {g=1}g' file

Thank you for the reply.

But i'm getting blank output.

As the field separator is "|" (not blank; sorry, i didn't mention this in my original post) i tried below but getting blank output. As i am using Solaris, i used "gawk".

#gawk -F"|" 'BEGIN{ toget="25829649" ;}$1=="JKL"{g=0}$1=="JKL" && $2==toget {g=1}g' rpk.in
#

Please note that whatever i am grepping (ex. 2222) need not be in the first line (line with AA).

Thanks again,
Prvn

Something like this perhaps?

$> cat test2
awk 'function printm() {if (m==1){for (r in A){print A[r]}};delete A;m=0} $1=="AA"{ printm()} {A[r++]=$0} /'$1'/{m=1} END{printm()}' rpk.in

Note that the part in red refers to the $1 of the surrounding shell script.

$> ./test2 1111
AA 1111 23 34
BB 45 56 78
CC 22 44
$>  ./test2 3333
AA 3333 46
BB 58 79
$>  ./test2 58
AA 3333 46
BB 58 79

If your file is '|' separated then use awk -F '|'

perl a.pl:

use Getopt::Std;
getopt('k');
local $/="--";
open FH,"sed 's/^AA /--AA /' yourfile.txt|";
while(<FH>){
        s/--//;
        print $_ if /\b$opt_k\b/;
}

Usage:

perl a.pl -k 1111
perl a.pl -k 2222

Thank you Scrutinizer!! It worked like a charm.

summer_cherry - Thank you, i will check your solution as well and let you know.

Derivated from ghostdog74 solution :

awk -v value=$1 '
/^AA/ { display = ($2 == value) }
display
' pv.dat

Jean-Pierre.