Tuesday, September 30, 2008

Calculate percentage using awk in bash


$ cat myde.txt
OC:4343
AF:5600
AS:1233
NA:6546
SA:3243

Output required: Calculate the percentage of each of the numbers.
i.e. required output:

4343(20.72 %)
5600(26.71 %)
1233(5.88 %)
6546(31.22 %)
3243(15.47 %)

Awk solution:


$ awk '{a[NR] = $2; sum+= $2 }
END {
for (i = 1; i <= NR; i++)
printf "%s(%2.2f %)\n", a[i],(100 * a[i])/sum
}
' FS=":" myde.txt

1 comment:

nag said...

How can i find the missing numbers in the following....
I have a series of numbers like the following...

703001
703002
703004
703008
703009
703010

I want to find the missing numbers in the series.
i.e., in this example the missing numbers are
703003
703005
703006
703007

I could find the difference of the numbers with the following

awk '{ar[NR]=$0}END{
for (i=1; i<=NR; i++){
printf"%6d-%6d=%6d\n",ar[i+1],ar[i],ar[i+1]-ar[i]
}' input

© Jadu Saikia www.UNIXCL.com