Display occurrences and count lines between them and after the last one

text processing

I have this file:

table_01 (id, field01, field02, field03, field04)
record_01
record_02
record_03
table_02 (id, field01, field02, field03)
record_01
table_03 (id, field01, field02, field03, field04)
record_01
record_02
table_04 (id, field01, field02, field03, field04, field04)
record_01
table_05 (id, field01, field02, field03, field04)
record_01
record_02
record_03
record_04

I want to have a script to display the lines
with the occurrence of the word “table
and display the number of lines between them
and the lines after the last occurrence.

So the output would be:

table_01 (id, field01, field02, field03, field04)
3
table_02 (id, field01, field02, field03)
1
table_03 (id, field01, field02, field03, field04)
2
table_04 (id, field01, field02, field03, field04, field04)
1
table_05 (id, field01, field02, field03, field04)
4

So far I have this script:

awk '$0 ~ /table/ {if (n) print NR-1-n; n=NR}' file

Its output is:

3
1
2
1

But this script doesn't display the lines
with the occurrence of “table”,
and doesn't display the lines after the last occurrence. 
How can I modify it to display what is missing?

Best Answer

Clearly, you’re 90% of the way there:

awk '/table/ {if (n) print NR-1-n; n=NR; print}
     END     {if (n) print NR-1-n}'             file

You don’t need $0 ~; that’s implied.

Related Question