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
awk '{s+=$1}END{print "ave:",(NR?s/NR:"NaN")}' RS=" " file
– Ed Morton
Jun 7 '16 at 12:11
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:\ /
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
awk '{s+=$1}END{print "ave:",s/NR}' file
– Manoel Stilpen Jul 5 '17 at 3:13