How to Use Awk If Else Statement with Examples

AWK, a powerful and versatile scripting language embedded in the bash shell, excels in data manipulation and reporting. Whether you’re a seasoned developer or a system administrator, AWK’s concise syntax and robust functionality make it an indispensable tool for processing text files and generating reports. In this guide, we will discuss how to use the if-else statement in the AWK command with practical examples.

The If Statement in AWK

The if statement is a fundamental control structure in AWK, enabling the execution of specific actions based on conditional evaluations.

Basic Syntax

The syntax for the if statement in AWK is straightforward:

awk '{ if (condition) { statement } }' [input_file]

When the specified condition evaluates to true, the statement enclosed within the braces is executed.

Download the practice file if you want to work through the problems using the examples provided below.

Example 1: Filtering Data Based on a Condition

Consider a scenario where you have a file named employees.txt with the following content:

IDNameDepartmentSalary
201AliceHR50000
202BobEngineering60000
203CharlieMarketing45000
204DavidEngineering70000
205EvaHR52000

To print the details of employees in the Engineering department, use the following AWK command:

awk '{
  if ($3 == "Engineering") {
    print "Employee ID:", $1, "Name:", $2, "Salary:", $4;
  }
}' employees.txt

Output

Example 2: Identifying High Salary Employees

Suppose you want to identify employees earning more than $50,000. The AWK command would be:

awk '{
  if ($4 > 50000) {
    print "High Salary Employee - ID:", $1, "Name:", $2, "Salary:", $4;
  }
}' employees.txt

Output

Example 3: Checking for Specific Values

Let’s say you need to find employees whose ID is 203. You can use the if statement as follows:

awk '{
  if ($1 == 203) {
    print "Employee Found - Name:", $2, "Department:", $3, "Salary:", $4;
  }
}' employees.txt

Output

The If-Else Statement in AWK

The if-else statement in AWK introduces a dual-path control structure, allowing you to specify actions for both true and false evaluations of a condition. This flexibility is vital for data processing tasks where different outcomes are required based on varying conditions.

Basic Syntax

The syntax for the if-else statement in AWK is as follows:

awk '{
  if (condition) {
    statement1
  } else {
    statement2
  }
}' [input_file]

If the specified condition evaluates to true, statement1 is executed. Otherwise, statement2 is executed.

Example 1: Categorizing Employees by Department

Consider a file named staff.txt with the following data:

IDNameAgeDepartment
301Emma28Sales
302Liam34Engineering
303Olivia29Marketing
304Noah42Sales
305Ava37Engineering

To categorize employees into Sales and non-Sales departments, you can use the following AWK command:

awk '{
  if ($4 == "Sales") {
    print "Sales Department - ID:", $1, "Name:", $2;
  } else {
    print "Non-Sales Department - ID:", $1, "Name:", $2;
  }
}' staff.txt

Output

Example 2: Evaluating Age Groups

Suppose you want to classify employees as either under 30 or 30 and above. The AWK command would be:

awk '{
  if ($3 < 30) {
    print "Under 30 - Name:", $2, "Age:", $3;
  } else {
    print "30 and Above - Name:", $2, "Age:", $3;
  }
}' staff.txt

Output

Example 3: Distinguishing High and Low Salaries

Let’s modify our dataset to include salaries and use an AWK command to differentiate between high and low earners. Assume staff_salaries.txt has the following structure:

IDNameDepartmentSalary
401JacobIT65000
402MiaHR48000
403WilliamIT73000
404SophiaMarketing52000
405JamesHR46000

To distinguish employees earning more or less than $50,000, the AWK command would be:

awk '{
  if ($4 > 50000) {
    print "High Salary - Name:", $2, "Salary:", $4;
  } else {
    print "Low Salary - Name:", $2, "Salary:", $4;
  }
}' staff_salaries.txt

Output

The If-Else-If Statement in AWK

The if-else-if statement in AWK provides a more complex conditional structure, allowing you to evaluate multiple conditions in sequence. This capability is crucial for scenarios where decisions depend on a variety of criteria.

Basic Syntax

The if-else-if statement in AWK follows this syntax:

awk '{
  if (condition1) {
    statement1
  } else if (condition2) {
    statement2
  } else if (condition3) {
    statement3
  } else {
    statementN
  }
}' [input_file]

AWK evaluates each condition in order. When a true condition is found, the corresponding statement is executed, and the remaining conditions are skipped.

Example 1: Classifying Employees by Age Group

Consider a file named workforce.txt containing the following data:

IDNameAgeDepartment
501Hannah24Finance
502Ethan31IT
503Isabella26Marketing
504Mason40Sales
505Lily22HR

To classify employees into young, middle-aged, and senior categories, use the following AWK command:

awk '{
  if ($3 < 25) {
    print "Young Employee - Name:", $2, "Age:", $3;
  } else if ($3 <= 35) {
    print "Middle-Aged Employee - Name:", $2, "Age:", $3;
  } else {
    print "Senior Employee - Name:", $2, "Age:", $3;
  }
}' workforce.txt

Output

Example 2: Grading Students Based on Scores

Assume you have a file named students_scores.txt with the following structure:

IDNameScore
601Ava85
602Ben92
603Chloe77
604Daniel65
605Emily58

To assign grades based on score ranges, you can use the following AWK script:

awk '{
  if ($3 >= 90) {
    print "Excellent - Name:", $2, "Score:", $3;
  } else if ($3 >= 75) {
    print "Good - Name:", $2, "Score:", $3;
  } else if ($3 >= 60) {
    print "Average - Name:", $2, "Score:", $3;
  } else {
    print "Needs Improvement - Name:", $2, "Score:", $3;
  }
}' students_scores.txt

Output

Example 3: Determining Discount Levels for Products

Consider a file named products.txt with the following data:

IDProductPrice
701Laptop1200
702Smartphone800
703Tablet300
704Headphones150
705Monitor400

To determine discount levels based on price, use the following AWK command:

awk '{
  if ($3 > 1000) {
    print "High Discount - Product:", $2, "Price:", $3;
  } else if ($3 > 500) {
    print "Medium Discount - Product:", $2, "Price:", $3;
  } else if ($3 > 100) {
    print "Low Discount - Product:", $2, "Price:", $3;
  } else {
    print "No Discount - Product:", $2, "Price:", $3;
  }
}' products.txt

Output

Using the Ternary Operator in AWK

The ternary operator in AWK provides a succinct way to perform conditional evaluations and execute one of two expressions based on a condition. This operator is especially useful for simplifying if-else statements, making your code more concise and readable.

Basic Syntax

The ternary operator in AWK follows the syntax:

(condition) ? expression1 : expression2

If the condition evaluates to true, expression1 is executed; otherwise, expression2 is executed.

Example 1: Categorizing Products by Stock Level

Consider a file named inventory.txt containing the following data:

ProductIDProductNameStock
101WidgetA150
102WidgetB50
103WidgetC200
104WidgetD30
105WidgetE75

To categorize products as “In Stock” or “Low Stock” based on a stock threshold of 100 units, use the following AWK command:

awk '{print ($3 >= 100) ? "In Stock - Product:" $2 : "Low Stock - Product:" $2}' inventory.txt

Output

Example 2: Assigning Pass or Fail Status to Students

Suppose you have a file named grades.txt with the following structure:

StudentIDNameScore
201Alice88
202Bob45
203Charlie76
204Dana59
205Eva91

To determine whether students have passed or failed based on a passing score of 60, you can use the ternary operator:

awk '{print ($3 >= 60) ? "Pass - Name:" $2 : "Fail - Name:" $2}' grades.txt

Output

Example 3: Identifying Expensive and Affordable Products

Consider a file named products_pricing.txt with the following data:

ProductIDProductNamePrice
301Laptop1200
302Mouse25
303Keyboard50
304Monitor300
305Desk150

To classify products as “Expensive” if their price is above $500 or “Affordable” otherwise, use the following AWK command:

awk '{print ($3 > 500) ? "Expensive - Product:" $2 : "Affordable - Product:" $2}' products_pricing.txt

Output

Conclusion

In this guide, we’ve delved into the versatility and power of the AWK scripting language, focusing on key constructs such as if statements, if-else statements, if-else-if statements, AWK program files, and the ternary operator. By mastering these elements, you can efficiently handle a wide range of data processing tasks, making AWK an indispensable tool for any data professional or enthusiast.

Share your love

Newsletter Updates

Stay updated with our latest guides and tutorials about Linux.

Leave a Reply

Your email address will not be published. Required fields are marked *