Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sum of columns using an array 2

Status
Not open for further replies.

maxtektips8

Technical User
Feb 1, 2007
4
NL
Hi,
With an input file like this

1,2,3,4,...,N
1,2,3,4,...,N
..
..
1,2,3,4,...,N

for N = 2 - a file with 2 columns only - using the following to calculate the sum of columns is okay :

{FS=","}
{s1+=$1;s2+=$2}
END{print s1 FS s2}

if N is big i suppose using an array would be more appropriate.
can anyone help ?

thanks
 
syntax error with the above (changed layout a bit, otherwise it only says line 1):

cat this_file | awk '
{
for (i=1;i<=NF;i++)
t+=$i
}

END {
for(i=1;i in t;i++)
print t
}
'

awk: syntax error near line 8
awk: illegal statement near line 8
awk: syntax error near line 8
awk: illegal statement near line 8
awk: illegal statement near line 11

is it the awk version used by the system ?
 
Hi

It works for me on Linux with [tt]gawk[/tt] and [tt]mawk[/tt], on CygWin with [tt]gawk[/tt] and on Windows with [tt]awk95[/tt].

Give us more details for the debugging. What [tt]awk[/tt] and shell are you using ?

Feherke.
 
Awk on Sun 5.8. with any shell. Had a try on a production machine and it works there so it must be the awk version installed on the environment i'm using. Is there any more portable way to rewrite it ?
 
more portable way
awk '
{ for(i=1;i<=NF;++i) t+=$i
if(n<NF)n=NF
}
END {
printf t[1]
for(i=2;i<=n;++i) printf ","t
printf "\n"
}
' this_file

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top