Can use sed. One way is to use a "sentinal", for example, a non-printable character that is absent from the input.
sed -n "s/SENTINAL//g;s/\(.*\)\(foo=\)\([0-9]*\)\(.*\)/SENTINAL\3/;/SENTINAL/!d;s/SENTINAL//;/./p"
shortened to
x=$(echo x|tr x '\34');
sed -n "s/$x//g;s/\(.*\)\(foo=\)\([0-9]*\)\(.*\)/$x\3/;/$x/!d;s/$x//;/./p"
Using flex is another option. Faster than AWK, Perl, sed and similarly ubiqitous.
flex -8iCrf -o/dev/stdout << eof|cc -xc -O3 -std=c89 -pedantic -W -Wall -static /dev/stdin
int fileno(FILE *);
#define J BEGIN
#define E ECHO
int x;
%option noyywrap noinput nounput
%s x1 x2
%%
foo=[^\n] yyless(1);J x1;x++;
<x1>[0-9]+ if(x==1)E;J x2;
<x2>\n E;x=0;J 0;
<x2>.
.|\n
%%
int main(){ yylex();exit(0);}
eof