0

I'm working on a small script to take 3 numbers in a single line, sum and average them, and print the result at the end of the line. I know how to use the paste command, but everything I'm finding is telling me how to average a column. I need to average a line, not a column. Any advice? Thanks!

2
  • 3
    Any sample input ? Commented Mar 23, 2016 at 14:30
  • 5
    wouldn't it be just ($1 + $2 + $3)/3? Commented Mar 23, 2016 at 14:31

2 Answers 2

2

awk to the rescue!

$ echo 1 2 3 | awk -v RS=' ' '{sum+=$1; count++} END{print sum, sum/count}'
6 2

works for any number of input fields

$ echo 1 2 3 4 | awk -v RS=' ' '{sum+=$1; count++} END{print sum, sum/count}'
10 2.5
Sign up to request clarification or add additional context in comments.

2 Comments

Or Perl: echo "1 2 3" | perl -pae '$_=eval(join"+",@F)/@F'
@andlrc There's no need to provide translations of an answer into another language in the comments. If you feel a perl solution is better, post it as an answer.
0

You can manipulate your line before giving it to bc. With bc you have additional possibilities such as setting the scale. A simple mean from 1 2 3 would be

   echo "1 2 3"  | sed -e 's/\([0-9.]\) /\1+/g' -e 's/.*/(&)\/3/' | bc

You can wrap it in a function and see more possibilities:

function testit {

   echo "Input $@"
   echo "Integer mean"
   echo "$@"  | sed -e 's/\([0-9.]\) /\1+/g' -e 's/.*/(&)\/'$#'/' | bc

   echo "floating decimal mean"
   echo "$@"  | sed -e 's/\([0-9.]\) /\1+/g' -e 's/.*/(&)\/'$#'/' | bc -l

   echo "2 decimal output mean"
   echo "$@"  | sed -e 's/\([0-9.]\) /\1+/g' -e 's/.*/scale=2; (&)\/'$#'/' | bc
   echo
}

testit 4 5 6
testit 4 5 8
testit 4.2 5.3 6.4
testit 1 2 3 4 5 6 7 8 9

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.