I never used awk much, if at all, so I have little experience with it (unlike
grep which I have used in a few occasions), which is why I didn't think of
using it.
AWK is a very simple programming language. Very simple to learn too,
especially if you know the basics of the languages that inspired it: C
(Boolean operators, conditional statements, loops, numerical,
string-processing functions, etc.), sed (mostly for the program structure,
conditions followed by actions, but sed-like substitutions are possible too),
and the shell (pipes, redirections, etc.). If you often need to process
structured text files, it is really worth learning AWK's basics: it will take
you a day of work, and you will save much time in the long run.
I will need your help to, first, understand the code you wrote.
First of all, I wrote the program on one single line. For clarity, you
should break the line. Any good text editor can auto-indent the program and
highlight its syntax (as long as the language is recognized: the first line
should be "#!/usr/bin/awk -f").
The program I wrote consists of one single action, between braces (which more
generally delimit "blocks" of instructions, as in C). That action is
unconditional, because no condition precedes "{". That means the action is
executed on every record. By default every line is a record (the record
separator, RS, can be redefined). It is the case here.
The program uses two "for" loops, "for (i = 1; i