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.
More on Text processing: grep, sed, awk, cut, sort, uniq
What are the most useful `grep` flags?BeginnerWhat is the difference between basic, extended and Perl regular expressions in grep?IntermediateWhat are the core `sed` commands you use in automation?BeginnerWhy does `sed -i` behave differently on macOS and Linux?IntermediateHow do you use variables inside a `sed` expression safely?AdvancedWhat is the structure of an `awk` program?Beginner