Office lunch time. JSingh, Vis and KKR were playing a game and they wanted me to count their scores.
I made a rough text file which took this form after completion of 2 rounds.
$ cat officegame.txt
Name|Round1|Round2
JSingh|0|20
Vis|50|0
KKR|20|20
JSingh|10|40
Vis|50|20
KKR|40|10
JSingh|40|60
Vis|30|20
KKR|90|20
JSingh|0|60
Vis|20|20
KKR|50|50
After 2 rounds, they asked me their individual total scores in each rounds. This is what I did for the same.
$ awk -F"|" '
NR==1 {print}
NR!=1 {OFS="|";a[$1]+=$2;b[$1]+=$3}
END{for (i in a){print i,a[i],b[i]}}
' officegame.txt
Output:
Name|Round1|Round2
Vis|150|60
JSingh|50|180
KKR|200|100
I sent them the output. JSingh asked me the breakdown of each individual score in each of the rounds.
I had to write this to achieve his requirement,
$ awk -F "|" 'NR > 1 {
if (n[$1] == $1) {
r1[$1] = r1[$1] "+" $2
r2[$1] = r2[$1] "+" $3
} else {
n[$1] = $1
r1[$1] = $2
r2[$1] = $3
}
}
END {
for (i in n) {
printf "%s [Round1={%s}, Round2={%s}]\n", n[i], r1[i], r2[i]
}
}' officegame.txt
Output:
Vis [Round1={50+50+30+20}, Round2={0+20+20+20}]
JSingh [Round1={0+10+40+0}, Round2={20+40+60+60}]
KKR [Round1={20+40+90+50}, Round2={20+10+20+50}]
Related post:
- sum of and group by using awk
- group-by clause functionality in awk
- awk associative array examples
No comments:
Post a Comment