Bash & Shell Scripting (50 Qs)•Part 3: Advanced Text Processing & Production Internals (Senior / Lead)
How do you use `BEGIN` and `END` blocks in `awk` for data aggregation?
senior LevelCode Examplebash-shellAdvanced Text Processing
In Simple Words:
BEGIN { ... }: Runs once before reading any input lines (setup headers, initialize variables).- Pattern Action
{ ... }: Runs once for every matching line. END { ... }: Runs once after all lines are processed (print summary totals/averages).
bash
# Sum total memory from ps and calculate average:
ps aux | awk 'NR>1 { sum += $4; count++ } END { print "Avg Memory: " sum/count "%" }'