keepcalculator

06 Numbers and Powers

Awk Flow Control: if, while, for Statements

Card No. 06·68153 · Updated · Standard formula, shown below

Yes, you can use flow control statements in awk — the language includes if, else, while, do-while, and for loops, plus break, continue, and next. These let you add logic beyond simple field-by-field processing, so you can filter, loop, and branch within your text-processing scripts.

What Flow Control Looks Like in awk

Awk is a small programming language designed for scanning and processing text files. Its core model is: read a record (usually a line), split it into fields, and run your program’s pattern-action rules. Flow control statements work inside those actions, just like in C or JavaScript.

Here’s a simple if example that prints lines where the third field is greater than 100:

awk '{ if ($3 > 100) print $1, $2 }' data.txt

You can also use if as a pattern, which is more idiomatic:

awk '$3 > 100 { print $1, $2 }' data.txt

Both work, but the second form is often clearer for simple conditions. For more complex logic, you’ll use the full statement form.

if and else: Making Decisions

The if statement follows the usual syntax:

if (condition) {
    # do something
} else if (other_condition) {
    # do something else
} else {
    # fallback
}

Conditions use comparison operators (==, !=, <, >, <=, >=) and logical operators (&&, ||, !). You can also test whether a field matches a regular expression with ~ or !~.

Example: classify students by score:

awk '{ if ($2 >= 90) grade="A"; else if ($2 >= 80) grade="B"; else grade="C"; print $1, grade }' scores.txt

Remember that awk treats a non-zero number or a non-empty string as true. So you can write if ($1) to test whether field 1 exists and is not zero.

Loops: while, do-while, and for

Awk provides three loop constructs. The while loop repeats as long as a condition is true:

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

The do-while loop runs the body at least once, then checks the condition:

awk '{ i=1; do { print $i; i++ } while (i <= NF) }' data.txt

The for loop is the most compact and common:

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

All three can be nested. You can also use break to exit a loop early and continue to skip to the next iteration.

Special Flow Control: next and exit

Beyond the standard loops, awk has two statements that change the main processing flow:

  • next — stops processing the current record and immediately reads the next one, skipping any remaining patterns and actions for that record.
  • exit — stops the entire awk program, jumping to the END block if one exists.

These are powerful for skipping lines or terminating early. For example, to skip comment lines:

awk '/^#/ { next } { print $0 }' config.ini

And to stop after the first 10 lines:

awk '{ print; count++; if (count == 10) exit }' data.txt

Common Pitfalls and How to Avoid Them

Here are the mistakes people make most often when using flow control in awk:

  • Forgetting braces — A single statement after if or a loop doesn't need braces, but multiple statements do. Always use braces for clarity.
  • Using = instead of == — In conditions, = assigns, == compares. This is a classic typo that can cause subtle bugs.
  • Off-by-one in field loops — Fields are numbered from 1, not 0. NF is the count, so the loop should go i=1; i<=NF; i++.
  • Modifying NF or fields inside a loop — Changing a field inside a loop can affect the loop condition if you're iterating over fields. Avoid modifying fields while iterating.

Practical Examples

Let's look at a few realistic uses of flow control in awk.

Summing a column with a condition:

awk '{ if ($2 > 0) sum += $1 } END { print sum }' data.txt

Finding the maximum value in a column:

awk 'NR==1 { max=$1 } { if ($1 > max) max=$1 } END { print max }' data.txt

Printing every other line:

awk '{ if (NR % 2 == 0) print $0 }' data.txt

Using a for loop to reverse fields:

awk '{ for (i=NF; i>=1; i--) printf "%s ", $i; print "" }' data.txt

Frequently Asked Questions

Can I use else if in awk?

Yes, awk supports else if chains, just like C. You can write as many else if blocks as needed, and the first true condition's block runs.

Is there a switch statement in awk?

Standard awk does not have a switch statement. However, gawk (GNU awk) provides a switch extension. If you're using gawk, you can use it; otherwise, use if-else chains.

Can I use break and continue in awk loops?

Yes, break exits the innermost loop, and continue skips to the next iteration. They work exactly as in C.

How do I loop over all fields in a record?

Use a for loop: for (i=1; i<=NF; i++) print $i. This iterates from field 1 to the last field, which is NF.

What is the difference between next and exit?

next skips the rest of the current record and moves to the next input line. exit stops the entire awk program immediately, optionally running the END block.

Can I nest loops and if statements in awk?

Yes, you can nest them arbitrarily deep. Just make sure your braces match and you use proper indentation for readability.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →