I want to group all the file contents based on the value of first column. It would be better if the output is in sorted form.
Input:
1 foo
2 bar
1 foobar
2 barbar
3 apple
4 banana
3 mango
5 orange
Expected output:
1 foo, foobar
2 bar, barbar
3 apple, mango
4 banana
5 orange
If I understand correctly, you're looking for
perl -lane 'push @{$k{$F[0]}},$F[1];
END{$"=", ";print "$_ @{$k{$_}}" for sort keys(%k)}' file
There's no reason to explicitly split the line, the -a
flag already does it for you. It will split each input line into the @F
array. So, here we create the %k
hash whose keys are the 1st fields and whose values are the corresponding lists of 2nd fields. Then, at the end, we sort the hash keys, set the list separator ($"
) to ,[space]
and print each key and its corresponding list of values.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments