0

I created a script that adds four numbers that you enter: Example:

./myawkaverage 8 7 9 4 
28

I need my script to add those four number and display the average so the results look like this:

Example:

./myawkaverage 8 7 9 4
The average is 7

I also need the script to accept negative numbers.

My script so far looks like this:

#!/bin/bash
echo $1 $2 $3 $4 | awk '
  {
    print sum3($1, $2, $3, $4)
  }
  function sum3(a, b, c, d) {
    return (a + b + c + d)
  }'

2 Answers2

1

Without error checking and use of a user-defined awk function, you could simplify the script to this:

#!/bin/bash
echo $1 $2 $3 $4 | awk '{sum=0; for(i=1; i<=NF; i++) sum += $i; print sum}'

or if you do not need to always output a number even if zero:

#!/bin/bash
echo $1 $2 $3 $4 | awk '{for(i=1; i<=NF; i++) sum += $i; print sum}'
fpmurphy
  • 4,636
1

Naming a function that sums 4 numbers "sum3" is an interesting choice, as is naming a script that sums numbers "myawkaverage" :-). Anyway...:

$ cat myawkaverage
#!/usr/bin/env bash

printf '%s\n' "$@" | awk '{sum+=$0} END{print sum}'

$ ./myawkaverage 8 7 9 4 28

$ ./myawkaverage 1 2 3 4 5 6 7 8 9 10 11 66

and if you're actually trying to write a script to get averages then:

$ cat ./myawkaverage
#!/usr/bin/env bash

printf '%s\n' "$@" | awk -v n="$#" '{sum+=$0} END{ave=(n ? sum / n : "NaN"); print sum, ave}'

$ ./myawkaverage 8 7 9 4 28 7

$ ./myawkaverage 1 2 3 4 5 6 7 8 9 10 11 66 6

$ ./myawkaverage 0 0 0

$ ./myawkaverage 0 NaN

Ed Morton
  • 31,617
  • Using NR instead of -v n would also work, as the values arrive one-per-line. – Paul_Pedant Oct 17 '20 at 20:06
  • @Paul_Pedant no, that'd fail when the script is called with no arguments because the printf would generate an empty line so within awk NR would be 1 while n is 0. There are other ways it could be handled of course. – Ed Morton Oct 17 '20 at 21:05
  • It will print 0 instead of NaN, but avoids the test in the END case. The OP "guaranteed" there would be 4 numbers, of course. I would probably test $# up front to give a clearer user diagnostic (NaN->Babushka->Grandmother). – Paul_Pedant Oct 18 '20 at 10:09
  • Right and I prefer to print NaN (or Inf) and I prefer not to test $# outside of the awk script as I prefer to have the output generated in only 1 place, inside the awk script. But there are several ways to handle it. – Ed Morton Oct 18 '20 at 13:48