D&C Lug - Home Page
Devon & Cornwall Linux Users' Group

[ Date Index ][ Thread Index ]
[ <= Previous by date / thread ] [ Next by date / thread => ]

Re: [LUG] AWK multipass



Andrew Rogers wrote:

Today I thought I would learn awk programming so that I could scale a list of numbers. It seems that awk only does one pass of a file. I need two passes, the first which simply adds all the numbers, the second which divides each number by the sum.

Any suggestions?

The file that I need to convert has one number per line, eg.

2.3e-7
4.2e-8
4.7e-8

Should convert to:

0.721
0.132
0.147

Thanks
Andrew

I gave up on awk and used the following perl program instead:

#!/usr/bin/perl -w

$filen=$ARGV[0];  #filename
$sum=0;

open(FILE, "< $filen");  #open file for input
while($line=<FILE>){
   $sum=$sum+$line;
}
close FILE;

open(FILE, "< $filen");  #open file for input
while($line=<FILE>){
   $num=$line/$sum;
   print "$num\n";
}
close FILE;

Regards
Andrew




-- The Mailing List for the Devon & Cornwall LUG Mail majordomo@xxxxxxxxxxxx with "unsubscribe list" in the message body to unsubscribe.



Lynx friendly