monk
monk

Reputation: 2115

Group second column based on first column awk

Can someone please help in parsing the following data. Below are the input, output and tried attempt details.

Input data:

foo 1
bar 12
foo 23
foo 45
bar 223
bar 123
bar 3478
foo 45
zoo 1
zoo 0987
foo 5

Output data:

foo 1 23 45 45 5

bar 12 223 123 3478 

zoo 1 0987

Attempt(Failed):

awk '{a[$1]=$2;next}END{for(i in a) print i,a[i]}' input
zoo 0987
foo 5
bar 3478

Upvotes: 0

Views: 50

Answers (1)

anubhava
anubhava

Reputation: 785196

You may try this awk:

awk '{map[$1] = map[$1] OFS $2} END {for (i in map) print i map[i] ORS}' file

zoo 1 0987

foo 1 23 45 45 5

bar 12 223 123 3478

If you want to maintain original order of keys then use:

awk '!($1 in map) {ord[++n] = $1} {map[$1] = map[$1] OFS $2} END {for (i=1; i<=n; ++i) print ord[i] map[ord[i]] ORS}' file

foo 1 23 45 45 5

bar 12 223 123 3478

zoo 1 0987

Upvotes: 1

Related Questions