Counting lines between two patterns

Hi Guys,

I have a file as follows:

 
wwe
khfgv
jfo
wwe
jhgfd
wwe
wwe
hoaha
hao
lkahe
wwe
 

I want to count the lines between the consecutive wwe's and store the count in variables. So for example the first variable value will be 2, (as there are two lines between the wwe's) second variable will be 1. The third variable value should be 0 and the fourth will be 3. I would prefer the awk solution and I guess using arrays will be better.

I started out with a simple statement:

awk '!/wwe/' file

but this does not give me missing lines (where there is no entry between the two consecutive wwe's.

Thanks in advance for your help.

awk ' /wwe/ { if ( f!="") {print f-1}; f=0;f1=1 } f1 { f++ } ' file

Thanks, that worked.

awk '/wwe/{if(p)print NR-p-1;p=NR}' infile
2
1
0
3
my $flag =0 ;
my $cnt = 0;
while(<DATA>){
	if(/wwe/){
		if($flag eq 0){
			$flag=1;
			next;
		}
		print $cnt,"\n" if $flag eq 1;
		$cnt=0;
	}
	else{
		$cnt++;
	}
}
__DATA__
wwe
khfgv
jfo
wwe
jhgfd
wwe
wwe
hoaha
hao
lkahe
wwe

Thanks,summer_cherry.

Now I want to print the lines between only the first two consecutive "wwe" lines. So my file output should be:

khfgv
jfo

How can I do this?

I tried using:

awk '! /wwe/,/wwe/' file

but that gives me


khfgv
jfo
wwe
jhgfd
wwe
hoaha
hao
lkahe
wwe
awk '/wwe/ && ++c <= 2 {getline; print}' file

That is giving me this output:

khfgv
jhgfd

I want:

khfgv
jfo

Sorry, I misread the question. It should be:

awk '/wwe/{getline; print; getline; print; exit}' file
awk '/wwe/{p++;next}p<2' infile

Sorry I was not clear on the question. I may have multiple lines between the two patterns for example:

wwe
khfgv
jfo
mmm
nnn
wwe
jhgfd
wwe
wwe
hoaha
hao
lkahe
wwe

I was looking for a more general solution. Your script will print only the two lines, but if I want to print all the lines ONLY between the first two consecutive wwe's. In this case I should get:

khfgv
jfo
mmm
nnn

Are the two print statements for the two lines?How can I modify the script to print all lines between the two wwe's?

Thanks for your patience on this.

To handle a variable number of records:

awk '/wwe/&&_++{exit}!/wwe/' infile

Thanks, radulov. It worked.

One last question: how can you modify the script if wwe is not the first word on the line; in other words, if my file was like this:

sss wwe
kkk khfgv
aaa jfo
qqq mmm
kjgfd nnn
rrr wwe
ttt jhgfd
uuu wwe
ooo wwe
ppp hoaha
ddd hao
fff lkahe
hhh wwe

and I want:

kkk khfgv
aaa jfo
qqq mmm
kjgfd nnn

Should I use $2 = in your awk script? Thanks again for your help.

Edit: I tried it and it worked. Sorry for the confusion.

No modification should be needed ...