Add and divide each numbers with the added number

Hi All,

I am stuck with this problem.

I have some 100000 (.dat) 1.dat, 2.dat,3.dat etc until 100000.dat files which look like this:

1.dat

1
2
3
4
0.99
4.54

All my files 1.dat until 100000.dat look the same but with different numbers.

I have to first add all the numbers in each file and divide each number with that number and store the result in .div file.

This is what I mean:
Lets take above example: 1.dat

  1. I add all the numbers present in 1.dat. The result is: 15.53

  2. Now I divide each number in this 1.dat file with 15.53

That is

1/15.53
2/15.53
3/15.53
4/15.53
0.99/15.53
4.54/15.53

and my final 1.div will look like this:

0.0643915
0.128783001
0.193174501
0.257566001
0.063747585
0.292337411

I have to follow the same procedure for all my other files that is create 2.div, 3.div for its corresponding .dat files that is for 4.dat, I create 4.div, 5.dat, I create 5.div and so on.

I have tried this but I guess there are minor mistakes. Moreover, it is not iterating over all the files in the directory.

BEGIN{ FS="," }
{
    for(i=1;i <=  NF;i++)
    {
        total+=$i;
    }
    numberColumn=NF;
}
END{
    for (i=1;i <= numberColumn;i++)
    {
        media=total/NR;
        printf("%.2f|%.2f\n",media);
    }
}

I am using Linux with BASH.

Try this...

#!/bin/bash

for file in *.dat
do
  out_file=$( echo ${file%%.*} ).div
  awk -v out_file=$out_file '
  { a=a+$0; b[++i]=$0} END{for(j=1;j<=i;j++){print b[j]/a > out_file} } ' $file
done

--ahamed

1 Like