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.
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.
Here is one method:
$ awk '{s+=$1}END{print "ave:",s/NR}' RS=" " file
ave: 54.646
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.
Edit: awk
is faster and it doesn't require reading the whole input to memory:
$ time seq 1e6|awk '{x+=$0}END{print x/NR}'>/dev/null
real 0m0.145s
user 0m0.148s
sys 0m0.008s
$ time seq 1e6|jq -s add/length>/dev/null
real 0m0.685s
user 0m0.669s
sys 0m0.024s
perl -lane '$a+=$_ for(@F);print "ave: ".$a/scalar(@F)' file
if you have multiple lines and you just need a single average:
perl -lane '$a+=$_ for(@F);$f+=scalar(@F);END{print "ave: ".$a/$f}' file
I had to find the average (time took for each ping request)
ping -c 5 www.youtube.com | grep time= | awk -F '[= ]' '{ sum += $11 } END { printf("%.2f ms\n", sum/NR) }'
-c
in ping
request is for numbers of icmp
requests to send.
-F
in grep
used to specify the field separators.
We can use printf
to control number of precision we want to display after the decimal points in our case it is 2 decimal points(%.2f
).
“NR
” is a special built-in variable of AWK
that stands for "number of records". This variable is used to deal with the number of records present in the specified files.
We are calculating average by diving sum
with NR
You can also find the sum
(sum of all time took by the ping request)
ping -c 5 www.youtube.com | grep time= | awk -F '[= ]' '{ sum += $11 } END { printf("%.2f ms\n", sum) }'