1

I'm trying to study for a test and one of the subjects are bash scripts. I have the following txt file :

123456 100 
654321 50 
203374111 86

I need to get the averages of the scores (the numbers in the second column).

This is what I have written :

cat $course_name$end | while read line; do
    sum=`echo $line | cut -f2 -d" "`
    let total+=$sum
done

I have tried with

while read -a line

and then

let sum+=${line[1]}

But I'm still getting the same error mentioned in the header.

1
  • No need for cut; read can handle the word splitting for you with with read id sum; do let total+=sum; done. id is just a placeholder for whatever the first column is. Commented Oct 8, 2013 at 13:57

4 Answers 4

1

I love AWK:

awk -F\* '{sum+=$3} END {print sum/NR}' x.txt

So in x.txt are values are stored. Please note that many answers don't actually compute the average, as they need to divide by the line numbers in the end. Often it will be performed by a wc -l < x.txt but in my solution you will get it almost for free.

Sign up to request clarification or add additional context in comments.

2 Comments

I have to say that I like the solution, but note that the OP says that I'm trying to study for a test and one of the subjects are bash scripts, so we can guess that is basically looking for a pure bash solution. By the way, I also love awk, it is such a powerful language!
I think that it should be sum+=$2 and there's no need to change the input separator - it looks like the OP was trying to make the numbers bold using **number** but it doesn't work in a code block.
0
cat your_file_name.txt | cut -f2 -d" " | paste -sd+ | bc

This should do the job!

Comments

0

You are very close, this works for me:

while read line; do
    sum=$(echo $line | cut -f2 -d" ")
    echo "sum is $sum"
    let total+=$sum
    echo "total is $total"
done < file

echo "total is $total"

As you can see, there is no need to use cat $course_name$end, it is enough to do

while read line
do

done < file

Also, it is more recommendable to use

sum=$(echo $line | cut -f2 -d" ")

rather than

sum=`echo $line | cut -f2 -d" "`

Or even

sum=$(cut -f2 -d" " <<< "$line")

Comments

0

There's no need to use cat as well as read; you can redirect the contents of the file into the loop. You also don't need to use let for arithmetic.

sum = 0
count = 0
while read id score; do
    (( sum += score )) && (( ++count ))
done < "$course_name$end"

echo $(( sum / count ))

This will give you an integer result, as bash doesn't do floating point arithmetic. To get a floating point result, you could use bc:

bc <<< "scale=2;$a/$b"

This will give you a result correct to 2 decimal places.

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.