Appending lines in a file

Hello,
I have a file like:

str1,"HEX"H,(39),info
str2,"HEX"H,(854548),info
str3,"HEX"H,'BGTOUR',info
str4,"HEX"H,(534322),info
str1,"HEX"H,,info
str3,"HEX"H,'Landing',info
str4,"HEX"H,'BG',info
str1,"HEX"H,,info
str3,"HEX"H,'Ay',info
str1,"HEX"H,(27),info
str2,"HEX"H,(854548),info
str4,"HEX"H,(534530),info

How can I append lines until it reaches next str1, output like that:

str1,"HEX"H,(39),info,str2,"HEX"H,(854548),info,str3,"HEX"H,'BGTOUR',info,str4,"HEX"H,(534322),info
str1,"HEX"H,,info,,,,,str3,"HEX"H,'Landing',info,str4,"HEX"H,'BG',info
str1,"HEX"H,,info,,,,,str3,"HEX"H,'Ay',info,,,,
str1,"HEX"H,(27),info,str2,"HEX"H,(854548),info,,,,,str4,"HEX"H,(534530),info

They are supposed to be four lines, each with 4 fields.
str1 is always there.
str2, str3 and str4 can be missing.
Is it possible to put commas for the empty spaces as it is marked in red above.

Thanks!

awk -F, 'BEGIN {
  p="str1,str2,str3,str4"
  ef = ",,,,,"
  n = split(p, t)
  }
$1 == t[1] && NR > 1 {
  for (i = 0; ++i <= n; ) 
    printf "%s%s", (t in r ? r[t] : ef), (i < n ? OFS : ORS)
  split(x, r)    
  }
{ r[$1] = $0 }
END {
  for (i = 0; ++i <= n; ) 
    printf "%s%s", (t in r ? r[t] : ef), (i < n ? OFS : ORS)
  }' OFS=,  infile
1 Like

Thank you very much Radoulov, it works perfectly!