Ok. The idea is to append the next line, for each cycle, into the holding space, deleting the already existing capital and adding commas
1h; When? For the first line. What? Put working space into holding space
1!H; When? Always except the first line. What? Append working space into holding space. Why? To concatenate the new line to what we have already done.
g; When? Always. What? Put holding space into working space. Why? To work on it.
s/\(.*\)\([A-Z]\) \(.*\)\n\2 \(.*\)/\1\2 \3,\4/; substitution processing
h; When? Always. What? Put working space into holding space. Why? To prepare the next cycle.
$!d; When? Always except the last line. What? Clear working space. Why? Not to see result on screen.
Remove it to see the evolution on screen.
Let's examinate the substitution:
When?
s/blabla/bloblo/ the first time
s/blabla/bloblo/2 the two first time
s/blabla/bloblo/g always
. -> any character
.* -> 0 or more character(s)
.+ -> 1 or more character(s)
.? -> 0 or 1 character (not sure. Maybe .\? )
\n -> end of line. Putting a new line (by N, G or H) is the way to concatenate multilines. You can choose to substitute \n or not.
^ -> beginning of line
$ -> end of line in regular expressions (but last line in the sed adressing system. Don't be confused)
What is the first block? Anything. Surely, what we have already done.
What is the second block? A capital.
What is the third block? Anything. Surely the numbers, separated by commas
What is the fourth block? Anything. Surely the last new number
What is the first \2? The same capital. Why not [A-Z]? Because any pair of capitals matches. Not only a capital twice.
The subtitution seems to delete the \n. Why can we see few lines? Because when you change the capital, the pattern is not recognized and the substitution is not done.
If I write 's/\n/ /g', would it write everything on a single line? No. The working space has no \n but is considered as a line. Use H,G,N.
Let's examinate your code:
sed '/^$/!{ 
you said "If the line is not an empty line". Why not saying "If there is something":
sed '/./{ ?
h 
Great to put into holding space. But if you never get the text back, it is useless.
N Remember that the cycle is accomplished for each line and then, a new cycle starts. Here, it will do what you want one line out of two. Because it has sent result to screen before a new N is executed.
Still any problem? ;-)