1

I have the following data:

St1 apt1
St1 apt2
St2 apt5
St3 apt6
St3 apt7
St3 apt8

I would like to merge the duplicate lines and separate the fields by comma and have 2 columns, for example:

St1 apt1,apt2
St2 apt5
St3 apt6,apt7,apt8

I tried the command bellow, but did not work as expected:

awk 'BEGIN{FS="\t"}; BEGIN{OFS="\t"}; { arr[$1] = arr[$1] $2 }   END {for (i in arr) print i arr[i] }'

The result was:

St1apt1apt2
St2apt5
St3apt6apt7apt8

Any suggestion?

1

Just a couple of tweaks:

$ awk '
    BEGIN{FS="\t"; OFS=FS}; 
    { arr[$1] = arr[$1] == ""? $2 : arr[$1] "," $2 }   
    END {for (i in arr) print i, arr[i] }
' data
St1    apt1,apt2
St2    apt5
St3    apt6,apt7,apt8
1
sed -e '
   :a
   $!N
   s/^\(\(\S\+\)\s\+.*\)\n\2\s\+/\1,/;ta
' yourfile

Results

St1 apt1,apt2
St2 apt5
St3 apt6,apt7,apt8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.