1

I have a log file consiste of 240 float digits in the following format:

5.4
5.1
5.2
5.4
5.4
4.9
5.0
5.2
5.5
5.3
5.6
5.4
5.1
5.3
5.3
5.1
5.2
..
4.8

Accesing to this log file in bash environment I need to compute mean value for this data (the sum of the elements devided by the number of elements) and then store the resulting value as a new variable that I am going to use inside the same bash script for some purposes e.g. I need to store a variable mean = 5.0 Is it possible to do it directly in one bash script ?

Hot JAMS
  • 197
  • 2
  • 6

1 Answers1

7

Using awk:

awk '{sum+=$1}END{print sum/NR}' file.log

To store it in a bash variable use command substitution:

variable=$(awk '{sum+=$1}END{print sum/NR}' file.log)

In order to change the precision you can use printf:

variable=$(awk '{sum+=$1}END{printf "%.1f", sum/NR}' file.log)
jesse_b
  • 37,005