1

Input file

steve,apples
steve,oranges
john,pears
john,oranges
mary,bananas
steve,plums
mary,nactarines

I want to get output like this:

steve:apples,oranges,plums
john:pears,oranges
mary:bananas,nectarines

Here is the one liner I have been trying to get to work:

awk -F, '{if(a[$1])a[$1]=a[$1]","$2; else a[$1]=$2;}END{for (i in a)print i ":" a[i];}' OFS=, inputfile

The output it gives is

,orangesrs
,plumsesples
,nactariness

It would appear that the string concatenation a[$1]=a[$1]","$2 is resulting in the original value of the array element to be overwritten to some degree. How can I carry out this concatenation correctly?

Incidentally, I get the same results on Centos, and Mac OSX.

3
  • 1
    I tested your awk line, it gave desired output here. Commented Jun 26, 2014 at 14:46
  • That's strange. The file I had was one given to me by a customer, thart I then modified/simplified to show this proof of concept. I just recreated the file from scratch, and hey presto, it works... so I wonder why that original file didn't work! Commented Jun 26, 2014 at 14:52
  • 4
    Arrrghhh! The file was from a Windows machine - it was the extra CR that was causing stuff to get overwritten. Lesson learnt! Commented Jun 26, 2014 at 14:59

1 Answer 1

2

You can try this:

awk -F, '{a[$1]=(a[$1]?a[$1]FS$2:$2)} END {for (i in a) print i":"a[i]}' file
mary:bananas,nactarines
john:pears,oranges
steve:apples,oranges,plums

PS After posted it, I see that this is the same as Kent posted, but no info on why deleted.

Sign up to request clarification or add additional context in comments.

1 Comment

@EdMorton I do forgetting :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.