I have the following data structure:
apples yellow
apples yellow
apples green
apples green
apples green
grapes yellow
grapes yellow
grapes yellow
grapes green
lemons yellow
lemons green
lemons green
Important: I don't know my list contains apples, grapes and lemons beforehand. If I need to count the number of times $1
is yellow
and then display $1
with the number of yellow
counts next to it, I can do this with GNU AWK:
awk '$2=="yellow" {yellowfruit[$1]++} END {for (fruit in yellowfruit) print fruit,yellowfruit[fruit]}'
...and get the expected result:
grapes 3
lemons 1
apples 2
How can I add another column which counts green occurences for each fruit type? I can't do for (fruit in yellowfruit,greenfruit)
or like bash: for (fruit in yellowfruit greenfruit)
I found my answer some time ago but never got around to post it here. It requires only one
for
loop and the conditional statements are clearer.Result: