Tested with OpenBSD awk
, GNU awk
and mawk
:
awk -F ',| +' '{ for (i = 2; i <= NF; ++i) { print $1, $i } }' data.in |
sort -u |
awk '{ f[$1] = (f[$1] ? f[$1] "," : "") $2 } END { for (k in f) { print k, f[k] } }'
The first awk
expands the given data into
Special c1
Special c2
Special c5
Special c7
Special c1
Special c2
Special2 C6
It uses both commas and multiple spaces as field delimiter and, for each record (line) of input, it prints the first field followed by each of the other fields in turn on separate lines. This assumes that there are no other spaces or commas on the lines other than where they will be properly interpreted as delimiters.
The sort
in the middle sorts it into
Special2 C6
Special c1
Special c2
Special c5
Special c7
It does a sort using the full line as the sorting key and discards any duplicate line.
The last awk
recombines the data into
Special c1,c2,c5,c7
Special2 C6
It does this by using the first field as a key into an associative array and stores the comma-separated concatenation of the corresponding data in the second field as the value. At the end, all collected data is printed.