Calculate column average using bash shell -

Question: Is there a way to calculate a average of a single column stored in a text file? For example my file contains:
$ cat file.txt
line1 4.5
line2 6
how do I get 5.25 ?
This is a companion discussion topic for the original entry at

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"


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


Thank you for the awk method! Brilliant.