$ cat file.txt line1 4.5 line2 6how do I get 5.25 ?
This is a companion discussion topic for the original entry at https://linuxconfig.org/calculate-column-average-using-bash-shell
$ cat file.txt line1 4.5 line2 6how do I get 5.25 ?
Joshua Peters
your near-lack of pipes made me sad, so I patched that right up for ya:
col=$(cat file1.txt | tr -s ' ' '\t' | cut -f2 | paste -s -d'+' -); n=$(echo $col | tr '+' '\n' | wc -w); bc -l <<< "($col)/$n"
asstBKR
You’re already using awk, just let it do the work:
$ echo "line1 4.5
> line2 6" > file
$ awk 'BEGIN {total=0}
> {total+=$2}
> END {printf("%.2f\n",total/NR)}
> ' file
5.25
$
Thank you for the awk method! Brilliant.