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

2 comments:

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

Karan Bohra said...

Task: Calculate the percentage of each of the numbers.

if='myde.txt'
< $if cut -d':' -f2 |
dc -e "
4k
[q]sq
[? z 0 =q dSM la+sa lk1+sk c l?x]s?
[LM lk 1-sk lk 0 <@]s@
0sa 0sk
l?x l@x
[n [(]n n [ %)]p s0]sp
[d la/100* r lpx z 0 <%]s%
l%x
"


Task: Find the missing numbers in a series (ensure 1 num/line AND no nonnum/empty lines in series.txt file)

cat series.txt |
dc -e "
[q]sq
[lnp s0]sa
[ln 1+ sn d ln !=a d ln !=b]sb
[? z 0 =q lbx c l?x]s?
?sn
l?x
"

© Jadu Saikia www.UNIXCL.com