awk match pattern and print lines till next blank line

Dear Experts,

Here is my input files which has various sections of data.

 SURVEY RESULT

NUMADDR             NUB       NUBA
4-9XXXXXXXXXXX      1244359    1099510
4-9YYYYYYYYYYY           692        586
4-2XXXXXXXXXXX           223        147
4-8YYYYYYYYYYY            1          1

SUMADDR             NUB       NUBA
4-9XXXXXXXXXXX      1244359    1099510
4-9YYYYYYYYYYY           692        586
4-2XXXXXXXXXXX           223        147
4-8YYYYYYYYYYY            1          1


TOTNSUB                NUB       NUBA
4-9XXXXXXXXXXX      128888    1099510
4-9YYYYYYYYYYY           692        586
4-2XXXXXXXXXXX           223        147
4-8YYYYYYYYYYY            1          1

TOTNSUBA             NUB       NUBA
4-9XXXXXXXXXXX      129999    1099510
4-9YYYYYYYYYYY           692        586
4-2XXXXXXXXXXX           223        147
4-8YYYYYYYYYYY            1          1

The below awk command to get data matching first column NUMADDR till number of lines specified in command.
I need only change here is instead of mentioning static number of lines for (y=0;y>4;y++) need all lines till next blank line.

 awk '{a[++i]=$0;}END{for (j=1;j<NR;j++) {if (a[j]~"NUMADDR") {for (y=0;y>5;y++) print a[j+y]}}}' file

Output should be as below

NUMADDR             NUB       NUBA
4-9XXXXXXXXXXX      1244359    1099510
4-9YYYYYYYYYYY           692        586
4-2XXXXXXXXXXX           223        147
4-8YYYYYYYYYYY            1          1

Dear experts,

Here below i tried and its worked

$ awk '$0~s{p=1;next}/^$/{p=0}p' s="NUMADDR" mgsvp_test.txt
4-9XXXXXXXXXXX      1244359    1099510
4-9YYYYYYYYYYY           692        586
4-2XXXXXXXXXXX           223        147
4-8YYYYYYYYYYY            1          1

eshaqur@SA-00001256 ~
$ awk '$0~s{p=1;next}/^$/{p=0}p' s="SUMADDR" mgsvp_test.txt
4-9XXXXXXXXXXX      1244359    1099510
4-9YYYYYYYYYYY           692        586
4-2XXXXXXXXXXX           223        147
4-8YYYYYYYYYYY            1          1

awk can do this during reading the input file - no need to store everything and process in the END section.

awk '$1~search {p=1} NF==0 {p=0}; p' search="NUMADDR" file

The p variable controls when to be printed. The bare p seclector without a following { action } defaults to { print } .

EDIT: Just seeing your previous post. It is quite similar to my solution.

2 Likes

G8 thanks a lot

its working and good enough

awk '$1~search {p=1} NF==0 {p=0}; p' search="NUMADDR" mgsvp_test.txt
NUMADDR             NSUB       NSUBA
4-9XXXXXXXXXXX      1244359    1099510
4-9YYYYYYYYYYY           692        586
4-2XXXXXXXXXXX           223        147
4-8YYYYYYYYYYY            1          1

How about

awk '/SUMADDR/,/^$/ ' file

or

sed -n '/SUMADDR/,/^$/p ' file

?