10.5 If-Else

To perform specific actions based on conditions, you can use if-else statements in the form of if(<condition>){action}, if(<condition>){action} else {action}, or if you want to add multiple else conditions you can extend the command to if(<condition1>){action1} else if(<condition2>) {action2}:

$ awk '{if ($1 == "ID") {++x} else {++y}} END {print x, "lines matched and", y, "lines did not match out of", x+y, "lines"}' BanthracisProteome.txt
5493 lines matched and 509872 lines did not match out of 515365 lines

Note: as we learned, undefined variables in awk are set to zero or empty at first use. Therefore we did not need to specify x and y in the beginning.

The if-command also makes it possible to store a variable until a condition is met. As en example imagine a file “zoo_inventory.txt” like that:

Species: Human
Daniel
Liam
Xenia
Species: Chimp
Betty
Tom
Species: Cat
Noobie
Nelson

So to print each individual with its corresponding species name, we can simply do:

$ awk '{if($1 ~ /Species/){sp=$2} else {print $1, "("sp")"}}' zoo_inventory.txt
Daniel (Human)
Liam (Human)
Xenia (Human)
Betty (Chimp)
Tom (Chimp)
Noobie (Cat)
Nelson (Cat)