0PricingLogin
Linux Command Line & Bash Scripting Mastery · Lesson

Patterns, Ranges, and BEGIN/END Blocks

Filter records with conditional patterns and produce headers and totals using BEGIN and END blocks.

What Are awk Patterns?

In awk, a pattern is a condition that controls whether an action block executes for a given input line. The general form is:

awk 'pattern { action }' file

If the pattern matches the current record, the action runs. If no action is given, awk prints the entire line by default. Patterns can be:

  • Regular expressions/regex/
  • Relational expressions$3 > 100
  • Compound expressions$1 == "ERROR" && $4 > 500
  • Range patterns/start/,/end/
  • Special patternsBEGIN and END

Understanding patterns is the gateway to using awk as a powerful data filter rather than just a column printer.

Regex Patterns to Filter Lines

The most common pattern type is a regular expression enclosed in forward slashes. awk tests each line against the regex and runs the action only on matches.

Below we filter an /var/log/syslog-style file to show only lines containing the word ERROR:

#!/usr/bin/env bash
# Simulate a log file and filter ERROR lines
log=$(cat <<'EOF'
2026-06-11 08:01:22 INFO  service started
2026-06-11 08:02:05 ERROR disk quota exceeded on /dev/sda1
2026-06-11 08:02:44 WARN  memory usage at 80%
2026-06-11 08:03:10 ERROR connection timeout to 10.0.0.5
2026-06-11 08:03:55 INFO  backup completed
EOF
)

echo "=== ERROR lines only ==="
echo "$log" | awk '/ERROR/ { print NR": "$0 }'

All lessons in this course

  1. Records, Fields, and Custom Separators in awk
  2. Patterns, Ranges, and BEGIN/END Blocks
  3. Aggregation with awk Arrays and Grouping
  4. awk Functions, printf Formatting, and Report Generation
← Back to Linux Command Line & Bash Scripting Mastery