On Sat, Jan 17, 2009 at 03:13:27AM -0600, Denny White spoke thusly:
>  On Thu, Jan 15, 2009 at 02:41:24PM +0000, Andreas Kahari spoke thusly:
> > 2009/1/15 igor denisov <denisovigor1...@rambler.ru>:
> > > Hi there
> > > Can not understand.
> > >
> > > input:
> > > 34523 9348 98493 82983
> > > 9485 83928 9283 9283
> > > 394 39934 293 8347
> > > 3456 9238 9283 9283
> > >
> > > awk 'NR==1 { for (i = 1; i <= NF; i++) {n=$i; next}}; {n-=$i} END {print 
> > > n}'
> > > input
> > >
> > > output:
> > > 21188 it is first column, why?
> > 
> > You should really take these questions to an awk forum, not to this
> > mailing list.
> > 
> > Your program reads the first record, and assigns its first column to
> > 'n' in a loop that is immediately exited (with 'next') and goes on to
> > read the remaining records.
> > 
> > For the remaining records, 'i' being still 1 from the prematurely
> > exited loop, the first column is subtracted from 'n'.
> > 
> > Regards,
> > Andreas
> > 
> > 
> > -- 
> > Andreas Kahari
> > Somewhere in the general Cambridge area, UK
> > 
> 
> Deleted original message, so replying to Andreas' message.
> 
> To sum by columns, do:
> awk '{for(i=1;i<=NF;i++)t[i]+=$i}END{for(i=1;i in t;i++)print t[i]}' \
> input
> 
> If you want to sum by lines, do:
> awk '{for(i=1;i<=NF;i++)t[i]+=$i}END{for(i=1;i in t;i++)print t[i]}' \
> input
> 
> If you want to total all the numbers at once you can do:
> awk '{for(i=1;i<=NF;i++)t[i]+=$i}END{for(i=1;i in t;i++)print t[i]}' \
> input
> 
> If I misunderstood what you want, like do you just want to total
> the first column, then:
> 
> awk '{print $1}' input | \
> awk '{for(i=1;i<=NF;i++)t[i]+=$i}END{for(i=1;i in t;i++)print t[i]}'
> 
> For another column, just change the '{print $1}' to whatever column
> you need. The gurus might and probably do know a better way, but
> that works. Hope this helps.
> 
> 
> Denny White
> 

Now I know I'm tired. I overlooked the subtraction part.

To subtract down through just the first column, do:

awk '{print $1}' input | \
awk 'NR==1 {n=$1; next}; {n-=$1} END {print n}'


For a 4 column file, to subtract through all 4 columns, do:

awk 'NR == 1 { d1 = $1; d2 = $2; d3 = $3; d4 = $4; next }{ d1 -= $1; \
d2 -= $2; d3 -= $3; d4 -= $4 } END { print d1, d2, d3, d4 }' input

And again, hope this helps.


Denny White 

-- 

() ascii ribbon campaign - against html e-mail
/\ www.asciiribbon.org - against proprietary attachments
===============================================================
GnuPG key  : 0x1644E79A  |  http://wwwkeys.nl.pgp.net
Fingerprint: D0A9 AD44 1F10 E09E 0E67  EC25 CB44 F2E5 1644 E79A
===============================================================

Reply via email to