Calculate average of each column in a file

前端 未结 1 990
说谎
说谎 2021-01-13 14:43

I have a text file with n number of rows (separated by commas) and columns and I want to find average of each column, excluding empty field.

A sample input looks lik

相关标签:
1条回答
  • 2021-01-13 15:05

    You can use this one-liner:

    $ awk -F, '{for(i=1; i<=NF; i++) {a[i]+=$i; if($i!="") b[i]++}}; END {for(i=1; i<=NF; i++) printf "%s%s", a[i]/b[i], (i==NF?ORS:OFS)}' foo
    2.5 4.5 4.5
    

    Otherwise, you can save this in a file script.awk and run awk -f script.awk your_file:

    {
        for(i=1; i<=NF; i++) {
            a[i]+=$i
            if($i!="") 
                b[i]++}
        } 
    END {
        for(i=1; i<=NF; i++) 
            printf "%s%s", a[i]/b[i], (i==NF?ORS:OFS)
    }
    
    0 讨论(0)
提交回复
热议问题