Bash operations

Bash operations

3

How to write a bash script that receives ANY integer numbers and print their mean with 2 decimal digit accuracy?


Bash

• 592 views

Here’s one such script:

#!/usr/bin/env bash

echo ${1} | awk -v RS=" " '{ n++; s+=$0 } END { printf("%.2fn", s/n) }'

To run it:

$ ./mean.sh "10 20 60"
30.00

Don’t forget quotation marks!

I got bored. Good luck in the coding exam / interview

#!/bin/bash
intarray=( "$@" ) ;
sum=0 ;
for i in ${intarray[@]} ;
do
  let sum+=$i ;
done ;
echo -e "--Sum is:t$sum"
mean=$(bc <<< "scale=2; $sum/${#intarray[@]}") ;
echo -e "--Mean is:t${mean}" ;

Then:

numbers=(1 2 3 4)
bash mean.sh "${numbers[@]}"
--Sum is:   10
--Mean is:  2.50

numbers=(37 8 20 6 29)    
bash mean.sh "${numbers[@]}"
--Sum is:   100
--Mean is:  20.00

#! /usr/bin/env bash
printf "%sn" ${1} | awk '{sum+=$0} END {printf("%.2fn", sum/NR)}'

to run it:

$ ./mean.sh "10 20 60"
30.00

if you are okay with datamash instead of awk, you can try this:

$  cat mean_dm.sh 

#! /usr/bin/env bash
printf "%sn" ${1} | datamash mean 1 median 1 -R 2

%  ./mean_dm.sh "10 20 60"

30.00

Advantage of having datamash is that you can print multiple statistics without writing much of the additional code:

$ cat ./mean_dm.sh 

#! /usr/bin/env bash
printf "%sn" ${1} | datamash mean 1 median 1 min 1 max 1 sstdev 1 -R 2

 $ ./mean_dm.sh "10 20 60"

30.00   20.00   10.00   60.00   26.46


Login
before adding your answer.

Traffic: 998 users visited in the last hour

Read more here: Source link