q's on file sort

I have a file below which has a list of users and roles with each row having unique combination of users and roles.

USER1 ROLE1
USER1 ROLE2
USER2
USER3 ROLE1
USER3 ROLE2
USER3 ROLE3
USER4 ROLE2
....
....

I am trying to create a script which sorts the above file to have all the roles in one line delimited by commas per user to look like below:

USER1 ROLE1,ROLE2
USER2
USER3 ROLE1,ROLE2,ROLE3
USER4 ROLE2
....
....

I was able to do this with the script below but when the input is very large it takes very long and takes up cpu usage so I was wondering if someone could tell me a faster way to achive this.

#!/bin/ksh

INPUT=$1

cut -d' ' -f1 $INPUT | sort -u > USER_LIST

while read USER
do
**** ROLES=$(echo "`grep $USER $INPUT | cut -d' ' -f2 | tr '\12' ','`" | sed -e
's/,$//g')

**** [[ $USER != $ROLES ]] && echo $USER $ROLES
**** [[ $USER = $ROLES ]] && echo $USER

done < USER_LIST

---------- Post updated at 12:34 PM ---------- Previous update was at 12:24 PM ----------

please ignore the astrix in the above script

awk 'NF{O[$1]=O[$1]?O[$1]","$NF:$0}END{for(i in O)print O}' file

Please use the [code] tags when you post data sample or code AND at any time you can edit your post and make corrections :wink:

I have another one however danmero's snippet is a bit more elegant.

awk '{user[$1]=$2?user[$1]","$2:""}END{OFS="";for(i in user) print i, user}' file 

danmero,
thank you very much for your help!
i'll put the script in code from next time.

@ripat your solution don't match the OP output requirement.

@stevefox Why you start a new/duplicate thread Create a script which sorts a file for the same problem ?