Reputation: 23
I have a test file:
user1 230230 1970
user2 313221 1978
user5 212334 1924
user3 313221 1987
user4 212345 1999
user3 123456 1983
user5 121212 1903
user2 234234 1992
user3 124690 1922
user5 092343 1945
when i run this script:
awk 'BEGIN{OFMT="%.2f"}{user_arr[$1]+=$2;user_arr_count[$1]+=1;}END{for (el in user_arr) {n=user_arr[el]/user_arr_count[el];print n}}' test
I get result
230230
273727.50
187122.33
212345
141963
but if i run
awk 'BEGIN{OFMT="%.2f"}{user_arr[$1]+=$2;user_arr_count[$1]+=1;}END{for (el in user_arr) {n=user_arr[el]/user_arr_count[el];print n" "el}}' test
I get rounds value:
230230 user1
273728 user2
187122 user3
212345 user4
141963 user5
why the result is rounded? Thanks for the explanation!
Upvotes: 2
Views: 1425
Reputation: 85785
In the first script you are printing the value n
and awk
knows to treat it as a number however in the second script you are printing n" "el
which is treated as a string because you are using string concatenation. What you want to do instead is print n,el
.
I would write the script like:
$ awk '{u[$1]+=$2;c[$1]+=1}END{for(i in u)print i,u[i]/c[i]}' OFMT="%.2f" file
user1 230230
user2 273727.50
user3 187122.33
user4 212345
user5 141963
Upvotes: 3