## Tuesday, September 29, 2009

### If else examples in awk - bash

Input file: Each line of 'num.txt' contains 2 numbers (say A and B).
`\$ cat num.txt34,140190,14089,120110,110210,115`

Required: Calculate and print percentage (A/B)*100 with the following conditions:

- If percentage is less than 100, print the calculated actual percentage
- If percentage is more than 100, print the percentage as 100

First solution:
`\$ awk 'BEGIN {FS=OFS=","}{if(\$1>\$2) {print \$0,100}else {print \$0,(\$1/\$2)*100}}' num.txtOutput:34,140,24.2857190,140,10089,120,74.1667110,110,100210,115,100`

Lets do some text alignment and formatting using awk.
`\$ awk 'BEGIN {FS="," ;  {printf "%-10s%-8s%s\n","A","B","% age"}}{if(\$1>=\$2) {printf "%-10s%-8s%s\n",\$1,\$2,100}else {printf "%-10s%-8s%2.2f\n",\$1,\$2,(\$1/\$2)*100}}' num.txtOutput:A         B       % age34        140     24.29190       140     10089        120     74.17110       110     100210       115     100`

Or a different look of the above script:
`\$ awk 'BEGIN {    FS="," ; FORMAT="%-10s%-8s%s\n" ;    {printf FORMAT,"A","B","% age"}}{    if(\$1>=\$2) {printf FORMAT,\$1,\$2,100}    else {printf FORMAT,\$1,\$2,(\$1/\$2)*100}}' num.txtOutput:A         B       % age34        140     24.2857190       140     10089        120     74.1667110       110     100210       115     100`

Another way of writing if else in AWK.
`\$ awk '{printf("%-10s%-8s%2.2f\n",\\$1,\$2, (\$1<=\$2) ? (\$1/\$2)*100 : 100)}' FS="," num.txtOutput:34        140     24.29190       140     100.0089        120     74.17110       110     100.00210       115     100.00`

Related post:

- Calculate percentage using awk in bash
- Align text with awk printf function

Mahesh Kharvi said...

Another way in awk.

awk -F, '{printf \$0","}\$1 < \$2{print \$1 * 100 / \$2;next}{print "100"}'

Unknown said...

Unknown said...

perl -wMstrict -F',' -lane '
BEGIN{ \$,=","; print qw/A B %age/ }
print \$_,
(((grep /^[-+]?\d+\$/, @F) < @F) ? "NaN" :
(\$F[1] == 0 ? "Inf" :
(\$F[1] <= \$F[0] ? 100 :
sprintf("%4.2f", 100*\$F[0]/\$F[1]))))

' |
sed -e '
1i\
.TS\
center,tab(,);\
c c c\
l l l.
\$a\
.TE

' | tbl - | nroff -Tascii -ms | grep '.'

Unknown said...

if='num.txt'

< \$if tr ',' '\040' |
dc -e "
4k
[q]sq
[n[,]nn[,]npc]sr
[LMd100*lM/rLMrlrxq]sp
[>p100LMLMrlrx]s@
[?z0=qdSMrdSMrl@xl?x]s?
l?x
" |
sed -e '
1i\
.TS\
tab(,);\
l l l.\
A,B,%age
\$a\
.TE
' | tbl - | nroff -Tascii -ms | grep '.'

Unknown said...

I have a datafile with the following data :
20160320110907: [1234567890, 2468012345]
20160320110907: [3333333333]
20170510091520: [2468012345, 0432186421]
20180118102025: [1234567890]
20180119110502:
Now how do I use awk to count number of occurrences such that the result is
Date(trimmed) GB1 UNIQUE
201603201109: 3 1
201705100915: 2 1
201801181020: 1 0
201801191105: 0 0 output could be like like this or separated for GB1 and UNIQUE