Control structures: if-else, while, for in AWK

In AWK, there are several control structures that can be used to control the flow of execution in a program. Here are some commonly used control structures:

– **if-else statements:** Used to conditionally execute a block of code.

`
  if (condition) {
    # code to execute if condition is true
  } else {
    # code to execute if condition is false
  }
  

Here is an example of using an if-else statement in AWK:

`
  awk '{ if ($1 > 10) print $1, "is greater than 10"; else print $1, "is less than or equal to 10" }' file.txt
  

This program reads each line of `file.txt`, checks if the first field is greater than 10, and prints a message depending on the result.

– **while loops:** Used to repeatedly execute a block of code while a condition is true.

`
  while (condition) {
    # code to execute while condition is true
  }
  

Here is an example of using a while loop in AWK:

`
  awk '{ i = 1; while (i <= NF) { print i, $i; i++; } }' file.txt
  

This program reads each line of `file.txt`, and loops over the fields of the line using a while loop. It prints the index and value of eachfield on a separate line.

- **for loops:** Used to repeatedly execute a block of code for a specified number of iterations.

`
  for (variable = start; variable <= end; variable++) {
    # code to execute for each iteration
  }
  

Here is an example of using a for loop in AWK:

`
  awk '{ for (i = 1; i <= NF; i++) { print i, $i; } }' file.txt
  

This program reads each line of `file.txt`, and loops over the fields of the line using a for loop. It prints the index and value of each field on a separate line.

- **for-in loops:** Used to loop over the elements of an array.

`
  for (variable in array) {
    # code to execute for each element
  }
  

Here is an example of using a for-in loop in AWK:

`
  awk '{ split($0, arr, " "); for (i in arr) { print i, arr[i]; } }' file.txt
  

This program reads each line of `file.txt`, splits the line into an array `arr` using the separator `" "`, and loops over the elements of the array using a for-in loop. It prints the index and value of each element on a separate line.

These are just a few examples of the control structures available in AWK. You can use them to implement complex logic and control the flow of execution in your programs.