Problem Statement
Explain awk programming features including variables, conditionals, loops, and built-in functions. Provide practical examples.
Explanation
Awk has built-in variables: NR (current record number), NF (number of fields), FS (field separator, default whitespace), RS (record separator, default newline), and OFS (output field separator). Example: awk '{print NR, $0}' file.txt adds line numbers. awk 'NF > 0' file.txt prints non-empty lines.
Conditionals: awk '$3 > 100 {print $1, $3}' file.txt prints first and third fields when third field exceeds 100. Use if-else: awk '{if ($3 > 100) print $1, "high"; else print $1, "low"}' file.txt. Pattern matching: awk '/error/ {count++} END {print count}' file.txt counts error occurrences.
Loops: awk '{for (i=1; i<=NF; i++) sum+=$i} END {print sum}' sums all fields in all lines. While loops: awk '{i=1; while (i<=NF) {print $i; i++}}' prints each field on separate line. Built-in functions include length(), substr(), toupper(), tolower(), split(), gsub(), and mathematical functions like sqrt(), sin(), cos().
Practical examples: awk -F: '{print $1, $3}' /etc/passwd prints usernames and UIDs. awk '{sum+=$1} END {print sum/NR}' calculates average of first column. awk '$3 ~ /^[0-9]+$/ {print $0}' prints lines where third field is numeric. Log analysis: awk '$9==200 {count++} END {print count}' access.log counts HTTP 200 responses. Master awk for complex data processing without external scripts.
