bash – awk if then else snippet

A clear example of the if/then/else structure formatting in awk.

1
2
3
4
5
6
7
8
9
$ 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

SOURCE: UNIXCL