Awk If, If Else, Else Statement or Conditional Statements – POFTUT

Awk If, If Else, Else Statement or Conditional Statements


Awk is a very popular text processing tool. Awk provides different functionalities and structures like programming languages. if - if else is a very useful conditional statement used to create decision trees. if - if else used to check the 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.

ismail 33 male
ahmet 5 male
elif 8 female

Awk If Statement

Awk if statement syntax is like below. We will check the condition and if the condition is met or true we will execute the code part. If not we simply skip if code block.

if (CONDITION)
{
   CODE
}

In this example we will look for the name ismail and then print his age.

{ 
  if($1 =="ismail") 
  { 
    print $2; 
    print $3 
  } 
}

We will save the awk script as if-program and call with awk -f parameter like below.

$ awk -f if-program data.txt
Awk If Statement
Awk If Statement

Or we can provide the script from bash like below.

Awk If Statement
Awk If Statement

Awk Else If Statement

What will happen if we have more than a single condition to check and execute the script. We can use else if statements for multi-condition situations. Syntax of else if is like below.

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 conditions like over 18 and below 18.

{ 
  if($2 > 17) 
  { 
    print $1" is adult" 
  } 
  else if($2 < 18) 
  { 
    print $1" is infant" 
  } 
 
}

When we run this code like below.

$ awk -f else-if-program data.txt
Awk Else If Statement
Awk Else If Statement

Awk Else Statement

While using if-else conditional statements we may need to specify default condition where it will meet if none of the other conditions is met. We can it else and put it to the end of the if-else if block. The syntax is like below

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 else-if because we do not need but they can be added without a problem if needed.

{ 
  if($3 == "male") 
  { 
    print $1" is male" 
  } 
  else 
  { 
    print $1" not male" 
  } 
 
}

We save this script as else-program and run like below.

$ awk -f else-program data.txt
Awk Else Statement
Awk Else Statement

LEARN MORE  Python Pass Statement

Leave a Comment