awk search between 2 digits a string

I would like to search between two [:digits:] a string. I thought this would be easy. The [:digit:] is always at the beginning of a line.

The code:

gawk '/^[0-9]/{d=$1},/searchstring/,/^(d+1)/'

or

gawk '/^[0-9]/,/searchstring/,/^[0-9]/'

did not return the desired result.

inputfile.txt
999 some text searchstring some text
some text, some text
1000 some text, some text
some text
1001 some text searchstring some text
some text
1002 ....

outputfile.txt
999 some text searchstring some text
some text, some text
1001 some text searchstring some text
some text

awk '/^[0-9]+/&&/searchstring/{print;getline;print}' file
1 Like
 
awk -v s="searchstring" '/^[0-9]/ && $0 ~ s {c=2;}c&&c--' input_file
1 Like

Thanks @panyam & @franklin52

panyams code returns a slightly different result than franklin52's code on my files. panyams is for me the more correct + suitable. I am a novice on awk, though I figured out that always the preceeding line with getline or {c=2} is returned. There are sometimes more preceeding lines. How would the code be if there are multiple lines? The next number is always one larger than the one where the search string is in.

inputfile.txt
999 some text searchstring some text
some text, some text
some text, some text
some text, some text
1000 some text, some text
some text
1001 some text searchstring some text
some text
some text, some text
1002 ....

awk '/^[0-9]+/{f=0}/^[0-9]+/&&/searchstring/{f=1}f' file
1 Like

Not tested throughly.

 
awk -v s="searchstring" '/^[0-9]/ && $0 ~ s {a=$0;c=1;next} /^[0-9]/ &&  $0 !~ s {print a;a="";c=0;next}c==1{a=a"\n"$0} END{print a}'  input_File
1 Like

Thanks @ Franklin52 & panyam

Amazing, two different approach, two different results but one desired and needed output.