LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Add values using awk (https://www.linuxquestions.org/questions/programming-9/add-values-using-awk-172817/)

Helene 04-21-2004 06:39 AM

Add values using awk
 
Hi,
I have this file:
Anni;2
Arna;9
Anni;4
Ally;1
Ally;1

I want the output to be:
Anni has: 6
Arna has: 9
Ally has: 2

This is my code so far:
awk -F';' { count[$1]++ } END { for (w in count) print w "has: " }' myFile

How can I find the sum of $2 for each name? I have tried several for loops and incremental variables, but I doesn't seem to work for me.

I appreciate any help!
- Helene

jim mcnamara 04-21-2004 10:50 AM

Code:

  cat file | sed 's/;/ has: /g' > newfile
It isn't awk but it should work as you wanted.

mfeat 04-21-2004 11:21 AM

sort file | awk -F\; '($1 != prev && NR != 1) {print prev" has "sum; sum=0} {sum+=$2; prev = $1}END{print $1" has "sum}'

mfeat 04-21-2004 11:24 AM

awk -F';' '{ count[$1]+=$2 } END { for (w in count) print w " has: "count[w] }' file

Helene 04-21-2004 06:30 PM

Thanks for help! I'll use the last one which was the one closest to my way of doing it :study:


All times are GMT -5. The time now is 03:46 PM.