## 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"}'