1

I have a small txt file:

Josh 10
Bill 10
Samanda 30

The sum of all nums is 50. How can I use this sum for dividing values on each row?

0.2 # 10/50
0.2 # 10/50
0.6 # 30/50

My awk script doesn't work as expected:

BEGIN {
sum += $2;
}
{
print $2/sum
}

It returns 0.

0

2 Answers 2

3

Could you please try following, written and tested with shown samples in GNU awk.

awk '
{
  val[NR]=$2
  sum+=$2
}
END{
  for(i=1;i<=NR;i++){
    print sum?val[i]/sum:0
  }
}
' Input_file

Explanation: Adding detailed explanation for above.

awk '                            ##Starting awk program from here.
{
  val[NR]=$2                     ##Creating array val whose index is  current line number and value is 2nd field of current line.
  sum+=$2                        ##Creating sum which has 2nd column value in it which is keep on getting added in it.
}
END{                             ##Starting END block of this code here.
  for(i=1;i<=NR;i++){            ##Starting a for loop from i 1 to till value of count here.
    print sum?val[i]/sum:0       ##Printing val[i]/sum value here if sum is NOT NULL else printing 0 here.
  }
}
' Input_file                     ##Mentioning Input_file name here.
Sign up to request clarification or add additional context in comments.

Comments

2

BEGIN is true before any input file is open which is why your sum += $2 in your script does nothing but set sum to zero.

$ awk 'NR==FNR{sum+=$2; next} {print (sum ? $2/sum : "NaN")}' file file
0.2
0.2
0.6

The ternary is to protect against dividing by zero if sum is zero.

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.