Create a script which sorts a file

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

Hello,

Per our forum rules, all threads must have a descriptive subject text. For example, do not post questions with subjects like "Help Me!", "Urgent!!" or "Doubt". Post subjects like "Execution Problems with Cron" or "Help with Backup Shell Script".

The reason for this is that nearly 95% of all visitors to this site come here because they are referred by a search engine. In order for future searches on your post (with answers) to work well, the subject field must be something useful and related to the problem!

In addition, current forum users who are kind enough to answer questions should be able to understand the essence of your query at first glance.

So, as a benefit and courtesy to current and future knowledge seekers, please be careful with your subject text. You might receive a forum infraction if you don't pay attention to this.

Thank you.

The UNIX and Linux Forums

Something like this :

awk '{ a[$1]=a[$1]$2"," ;next } END {for ( i in a) {print i" "a }}' File_name |sed 's/,$//'