Help with merge row if share same column info

Input file:

32568        SSO7483
32568        SSO7486
117231       SSO1293
117231       SSO1772
178081       SSO3076
178081       SSO3077
222417       porA-2
222417       porB-2
263778       SSO1245
263778       SSO0509
.
.

Desired output:

32568        SSO7483,SSO7486
117231       SSO1293,SSO1772
178081       SSO3076,SSO3077
222417       porA-2,porB-2
263778       SSO1245,SSO0509
.
.

I wanna merge the column 2 info if both row share same column 1 info.
I did try this code,

awk '{if (a[$1])a[$1]=a[$1]","$2;else a[$1]=$2;}END{for (i in a)print i, a;}' Input_File
263778 SSO1245,SSO0509
117231 SSO1293,SSO1772
32568 SSO7483,SSO7486
222417 porA-2,porB-2
178081 SSO3076,SSO3077
.
.

It worked as what I want but it will change the orientation of column 1 which make me confuse :frowning:

Thanks for any advice.

Hello perl_beginner,

If you are not bothered about the output's sequence(Means it may differ from the Input_file input sequence), then following may help you.

awk '{A[$1]=A[$1]?A[$1] OFS $NF:$NF} END{for(i in A){print i "\t" A}}' OFS=,   Input_file
 

Output will be as follows.

263778  SSO1245,SSO0509
117231  SSO1293,SSO1772
32568   SSO7483,SSO7486
222417  porA-2,porB-2
178081  SSO3076,SSO3077
 

If you need output to be in same order as in Input_file, then following may help you in same.

awk 'FNR==NR{A[$1]=A[$1]?A[$1] OFS $NF:$NF;next} ($1 in A){print $1 "\t" A[$1];delete A[$1]}' OFS=,  Input_file  Input_file

Output will be as follows.

32568   SSO7483,SSO7486
117231  SSO1293,SSO1772
178081  SSO3076,SSO3077
222417  porA-2,porB-2
263778  SSO1245,SSO0509
 

Thanks,
R. Singh

1 Like

Try also

awk '   
$1 != LAST      {if (NR != 1) printf "%s", RS
                 printf "%s", $0
                 LAST = $1
                 next
                }
                {printf ",%s", $2
                }
END             {printf "%s", RS
                }
' file
32568        SSO7483,SSO7486
117231       SSO1293,SSO1772
178081       SSO3076,SSO3077
222417       porA-2,porB-2
263778       SSO1245,SSO0509
1 Like

Thanks again, Singh :slight_smile:
It worked perfect ^.^

---------- Post updated at 10:18 AM ---------- Previous update was at 10:18 AM ----------

Thanks, RudiC.
Again you help me a lot :slight_smile:

Really many thanks to you.