Interview Prep/Shell Scripting/Text processing: grep, sed, awk, cut, sort, uniq

How do you pass shell variables into `awk`?

AdvancedConceptText processing: grep, sed, awk, cut, sort, uniq
Answer

Use -v, never splice a variable into the program text.

threshold=90
df -P | awk -v t="$threshold" 'NR > 1 {sub(/%/, "", $5); if ($5+0 >= t) print $6, $5"%"}'

ENVIRON_VAR=prod awk 'BEGIN {print ENVIRON["ENVIRON_VAR"]}'

awk "{print \$$col}" works but is fragile, and splicing untrusted input into awk code is code injection (awk can run system()). Note that -v processes backslash escapes; use ENVIRON[] for raw values.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Text processing: grep, sed, awk, cut, sort, uniq