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

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Click here to start participating now! Also, check out the New User Guide.

to calculate column total

Reply to Message Icon

Name: Nick
Date: October 10, 2002 at 07:07:50 Pacific
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



Sponsored Link
Ads by Google

Response Number 1
Name: James Boothe
Date: October 10, 2002 at 07:28:41 Pacific
Reply:

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}


0

Response Number 2
Name: Jerry Lemieux
Date: October 17, 2002 at 18:35:12 Pacific
Reply:

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



0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More


unix kill



Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: to calculate column total

how to calculate date (urgent) www.computing.net/answers/unix/how-to-calculate-date-urgent/5352.html

How to calculate the time interval www.computing.net/answers/unix/how-to-calculate-the-time-interval-/7780.html

displaying words in a row to column www.computing.net/answers/unix/displaying-words-in-a-row-to-column/4945.html