Transfered from Linux Config:
Question:
Is there a way to calculate a average of a single column stored in a text file? For example my file contains:
how do I get 5.25 ?Code:$ cat file.txt line1 4.5 line2 6
Answer:
One way to do this is to use combination of bash for loop, cut, echo and bc commands. Execute the code below, assuming that file.txt is in your current working directory:
and here is a shell script version of the above command so we can see what is happening in more detail:Code:$ count=0; total=0; for i in $( awk '{ print $2; }' file.txt );\ do total=$(echo $total+$i | bc ); \ ((count++)); done; echo "scale=2; $total / $count" | bc 5.25
For each line in file.txt we extract a second column with awk ( $i ). Then we use echo and bc command to add all numbers $i to get a total $total. The script also stores a number of loops $count. The last line uses echo and bc commands to calculate average with two decimal points.Code:#!/bin/bash count=0; total=0; for i in $( awk '{ print $2; }' file.txt ) do total=$(echo $total+$i | bc ) ((count++)) done echo "scale=2; $total / $count" | bc
awk only method:
You can also try use awk command:
Code:$ awk '{ total += $2; count++ } END { print total/count }' file.txt 5.25


Reply With Quote
