Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scripts for computing the average of a list of numbers in a data file

Tags:

bash

sed

awk

The file data.txt contains the following:

1.00 1.23 54.4 213.2 3.4 

The output of the scripts are supposed to be:

ave: 54.646 

Some simple scripts are preferred.

like image 881
JackWM Avatar asked Mar 28 '13 12:03

JackWM


People also ask

How do I get the average of a column in Linux?

To print mean values of all columns, assign totals to array @t: perl -lane 'for $c (0.. $#F){$t[$c] += $F[$c]}; END{for $c (0.. $#t){print $t[$c]/$.}}

What is the average of the list?

Average is the sum of elements divided by the number of elements. Examples: Input : [4, 5, 1, 2, 9, 7, 10, 8] Output : Average of the list = 5.75 Explanation: Sum of the elements is 4+5+1+2+9+7+10+8 = 46 and total number of elements is 8.

How do I sum and average numbers in a text file?

with open ('abc.txt') as fh: sum = 0 numlines = 0 for line in fh: n = line.split (':') [-1] sum += float (n) numlines += 1 average = sum / numlines print average this might work, but is terribly unidiomatic in Python. Try to avoid using the str.find commands.

How to calculate the average/mean in JavaScript?

In this case, we have 3 numbers. That means that in order to get the average number, we must divide 3 into 6, which gives us 2. Now, lets take the formula above and apply it to JavaScript. Calculating the average / mean using JavaScript. Take a look at the following example:

How to calculate average of numbers in a list in Python?

For calculating average, take the sum of numbers in list & divide sum with number of elements in list. All Programs Simple Python Programs Decision Making Loop Functions Files Arrays or List


2 Answers

Here is one method:

$ awk '{s+=$1}END{print "ave:",s/NR}' RS=" " file ave: 54.646 
like image 66
Chris Seymour Avatar answered Sep 29 '22 17:09

Chris Seymour


Another option is to use jq:

$ seq 100|jq -s add/length 50.5 

-s (--slurp) creates an array for the input lines after parsing each line as JSON, or as a number in this case.

Or in the OP's case:

tr \  \\n<file|jq -s add/length|sed s/^/ave:\ / 
like image 24
nisetama Avatar answered Sep 29 '22 17:09

nisetama