Computing.Net > Forums > Unix > to calculate column total

to calculate column total

Reply to Message Icon

Original Message
Name: Nick
Date: October 10, 2002 at 07:07:50 Pacific
Subject: to calculate column total
OS: unix
CPU/Ram: 256
Comment:

Hi,

I need help. I have the following input file:

TT,23423.11
YIE,1290.45
SIA,23477.92
...
...

I need a script that will sum up the value from the second column of this file and output a total value.

Thanks


Report Offensive Message For Removal

Response Number 1
Name: James Boothe
Date: October 10, 2002 at 07:28:41 Pacific
Subject: to calculate column total
Reply: (edit)

awk -F"," '{col2=col2+$2}
END {printf "Total: %12f\n",col2}' myfile

or to round to two decimal places, use:

printf "Total: %12.2f\n",col2}


Report Offensive Follow Up For Removal

Response Number 2
Name: Jerry Lemieux
Date: October 17, 2002 at 18:35:12 Pacific
Subject: to calculate column total
Reply: (edit)

The awk solution above is best for what you are trying to do. However, floating point can be done in the shell by piping a string to bc. An example:

#!/bin/sh

IFS=,
string="0"

while read col1 col2
do
if [ col2 != "" ]
then
string="$string+$col2"
fi
done < junk1.dat
echo "scale=2;$string" | bc

The ouput from your data file is:

48191.48



Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: to calculate column total

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software