1

I have a file that looks like:

381932
148457
304268
254699

I would like to write a shell script that returns each line as fraction of total:

0.350603476
0.1362796
0.279309978
0.233806946

How can I do this using in a shell script?

cm007
  • 1,352
  • 4
  • 20
  • 40

3 Answers3

1

Using &

#!/bin/bash

total=$(echo $(<file) | tr ' ' '+' | bc)
while read num; do echo "scale=9;$num/$total" | bc; done < file
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
1

awk may help:

awk '{s+=$1;a[NR]=$1}END{for(i=1;i<=NR;i++)printf "%.9f\n", a[i]/s}' file 

output:

0.350603476
0.136279600
0.279309978
0.233806946
Kent
  • 189,393
  • 32
  • 233
  • 301
1

With reference to this question:

sum=$(perl -nle '$sum += $_ } END { print $sum' file)
awk -v "sum=$sum" '{print $1/sum}' file
0.350603
0.13628
0.27931
0.233807

The question requires 2 passes through the file: once to calculate the sum and once to print the fraction.

Another approach is to store the lines as you do the sum:

awk '{sum += $1; n[NR]=$1} END {for (i=1; i<=NR; i++) print n[i]/sum}' file

This has higher memory requirements, worth noting if your file is very large.

Community
  • 1
  • 1
glenn jackman
  • 238,783
  • 38
  • 220
  • 352