When I said that my <code> example was extemporaneous, that is precisely what I meant: “do not copy-and-paste this snippet into your home directory and expect it to compile.” I have only a very limited amount of time to devote to responding to this forum, and so I often speak in generalizations that I expect my colleagues to understand.
I personally do not ascribe to the notion that any web-site should undertake to be “a code-writing service,” although on this point I might differ from that of other Monks here. The essential point of my reply, and which I hope will indeed prove useful to the OP, is that “this use-case is not exactly new.”
Moving our attention, now, away from the syntax errors and on to the essential point . . .
This is exactly the sort of use case that The Larry™ (ommm ...) was faced with, all these years ago, when he first looked at the awk tool and found it wanting. I will reserve judgment as to why this approach was not offered first, since its very obvious advantages it that it makes minimal prior assumptions about the structure of the input file. (As you plainly see, it classifies the lines first, and sorts-them-out later.) My point is not to judge anything or anyone else, but simply to point out that this approach is both valid, and old.