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.txt
34,140
190,140
89,120
110,110
210,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.txt

Output:
34,140,24.2857
190,140,100
89,120,74.1667
110,110,100
210,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.txt

Output:
A B % age
34 140 24.29
190 140 100
89 120 74.17
110 110 100
210 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.txt

Output:
A B % age
34 140 24.2857
190 140 100
89 120 74.1667
110 110 100
210 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.txt

Output:
34 140 24.29
190 140 100.00
89 120 74.17
110 110 100.00
210 115 100.00

Related post:

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

2 comments:

Mahesh Kharvi said...

Another way in awk.

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

Jadu Saikia said...

@Mahesh, thanks. Your comments are always valuable. Thanks.

© Jadu Saikia www.UNIXCL.com