calculate and print the average value of strings in a column

后端 未结 1 1536
[愿得一人]
[愿得一人] 2020-12-11 12:30

I got a .txt file with 2 columns of values. They are 2D coordinates, so the first column represent the x value and the second one is the z value. Unfortunately there are som

相关标签:
1条回答
  • 2020-12-11 13:01

    This is one way with awk:

    $ awk '{a[$1]+=$2; ++b[$1]} END {for (i in a) print i, a[i]/b[i]}' file
    435.212 108.899
    435.25 108.9
    435.238 108.9
    435.262 108.9
    435.275 108.9
    

    Explanation

    {a[$1]+=$2; ++b[$1]}

    • Store the z values (2nd column) in the array a.
    • Store the amount of elements for each x value (1st column) in the array b.

    END {for (i in a) print i, a[i]/b[i]}'

    • Print the result looping through the values stored in the array.

    To have another number format (4 float values for example) you can also use:

    printf "%d %.4f\n", i, a[i]/b[i]
    
    0 讨论(0)
提交回复
热议问题