1836528 Members
3780 Online
110101 Solutions
New Discussion

Adding up columns

 
SOLVED
Go to solution
Dave Walley
Frequent Advisor

Adding up columns

Hi.

I have to write a script to total a column of numbers. For example I want to total the first column. I am using a csh to get the data up to this point.

3497796 /dbs
3479374 /dbs2
5799894 /dublin
440128 /dublin2

Any help

Dave
why do i do this to myself
5 REPLIES 5
Francisco J. Soler
Honored Contributor

Re: Adding up columns

You can use the awk. For example.
awk 'BEGIN {total=0} {total+=$1} END {print total}' filein

You can redirect the stdout to another file.

If you want to print out all stdin you can modify the script and type in something like:

awk 'BEGIN {total=0} {total+=$1 ; print } END {print total}' filein

I hope this helps.
Linux?. Yes, of course.
Brian M. Fisher
Honored Contributor
Solution

Re: Adding up columns

You can also do the following for nicer output:

commands | awk 'BEGIN {total=0}{total += $1}
END {printf("%.2f Gign",total/(1024*1024))}'

XXX.XX Gig

Brian
<*(((>< er
Perception IS Reality
Brian M. Fisher
Honored Contributor

Re: Adding up columns

I made a typing mistake, it should be Gign instead of Gign

Brian
<*(((>< er
Perception IS Reality
Brian M. Fisher
Honored Contributor

Re: Adding up columns

The problem seems to be the backslash does not transfer to the postings:

It should be Gig"backslash"n

Brian
<*(((>< er
Perception IS Reality
Alan Riggs
Honored Contributor

Re: Adding up columns

The aboce replies are correct. For simplicity, though, the BEGIN, END, and initialization statements are not required. You can simply do:

| awk 'total+=$1 {print total}'

(note: this provides a running total. You do need the END statement (or a pipe to tail -1) if you want only the final total.)

ex: bdf|awk 'total+=$3 {printf("%.2f Gig|n",total/1024/1024)}'
provides a total of disk space used on a system. (note: |==backspace in the above.)