QA
Intermediate LevelLinux Commands & SysAdmin

How do BEGIN and END blocks and associative arrays work in advanced awk scripts?

❓ Interview Prompt: Explain advanced awk features: BEGIN block (initialization), END block (summary reporting), associative arrays, and counting frequencies.

Advanced awk scripts structure data aggregation using explicit execution blocks:

•
'BEGIN { ... }': Executes ONCE before reading input lines (used for headers or setting separators).
•
Main Block '{ ... }': Executes for EVERY input line.
•
'END { ... }': Executes ONCE after processing all lines (used for summary calculations).
•
Associative Arrays: Hash maps storing key-value frequencies ('count[$1]++').

Code Implementation Example

bash
# Count and report HTTP status code frequency breakdown from web access log
awk '{ status[$9]++ } END { for (code in status) print code, status[code] }' /var/log/nginx/access.log | sort -nr -k2
💡Counting HTTP status code frequencies using advanced awk associative arrays.
🎯 Interview Key Takeaway

Use awk BEGIN and END blocks alongside associative arrays to calculate data summaries and frequency breakdowns.

#awk#Associative Arrays#BEGIN END#Intermediate
Back to all Linux Commands & SysAdmin Questions→

More Linux Commands & SysAdmin Interview Questions

Beginner LevelLinux Commands & SysAdmin

How do Linux File Permissions (chmod, chown, chgrp) work in Octal and Symbolic notation?

Beginner LevelLinux Commands & SysAdmin

What is the Linux Filesystem Hierarchy Standard (/bin, /etc, /var, /usr, /opt, /tmp)?

Beginner LevelLinux Commands & SysAdmin

What are File Descriptors (0=stdin, 1=stdout, 2=stderr) and Redirection (>, >>, 2>&1)?