Awk If, If Else , Else Statement or Conditional Statements
Awk is very popular text processing tool. Awk provides different functionalies and structures like programming languages. if - if else
is very useful conditional statement used to create decision trees.
if - if else
used to check given situation or operations and run accordingly. For example we can check the age of the person and act accordingly if over 60 or below 60 .
Example Data
During learning awk if- if else statements we will use following file.
1 2 3 |
ismail 33 male ahmet 5 male elif 8 female |
Awk If Statement
Awk if statement syntax is like below. We will check condition and if the condition is met or true we will execute the code part. If not we simply skip if code block.
1 2 3 4 |
if (CONDITION) { CODE } |
In this example we will look for the name ismail
and then print his age.
1 2 3 4 5 6 7 |
{ if($1 =="ismail") { print $2; print $3 } } |
We will save the awk script as if-program
and call with awk -f
parameter like below.
1 |
$ awk -f if-program data.txt |

Awk If Statement
Or we can provide the script from bash like below.

Awk If Statement
Awk Else If Statement
What will happen if we have more than single condition to check and execute script. We can use else if
statements for multi condition situations. Syntax of else if
is like below.
1 2 3 4 5 6 7 8 9 |
if (CONDITION) { CODE } else if (CONDITION) { CODE } ... |
We can use more than if else
according to our needs.
In this example we will list persons with two different condition like over 18 and below 18 .
1 2 3 4 5 6 7 8 9 10 11 |
{ if($2 > 17) { print $1" is adult" } else if($2 < 18) { print $1" is infant" } } |
When we run this code like below.
1 |
$ awk -f else-if-program data.txt |

Awk Else If Statement
Awk Else Statement
While using if else conditional statements we may need to specify default condition where it will met if none of the other condition is met. We can it else
and put to the end of the if-else if
block. Syntax is like below
1 2 3 4 5 6 7 8 9 10 11 12 13 |
if (CONDITION) { CODE } else if (CONDITION) { CODE } ... else { CODE } |
In this example we will check the gender and given record is not male we will print a message. In this example we do not add elseif
because we do not need but they can be added without problem if needed.
1 2 3 4 5 6 7 8 9 10 11 |
{ if($3 == "male") { print $1" is male" } else { print $1" not male" } } |
We save this script as else-program
and run like below.
1 |
$ awk -f else-program data.txt |

Awk Else Statement