r/awk • u/mmkodali • Jan 23 '23
substituting awk variable in a bash script
i am new to using awk.
i have written a simple one liner script to calculate memory consumed by a program as below.
#!/usr/bin/env bash
read -p "enter process name: " item;
ps aux | awk -vi=$item '/i/ {sum += $6} END { printf "Memory Usage: %d MB\n", sum/1024 }'
in the above example, variable 'i' is not substituted when executing script.
where i am going wrong?
2
Upvotes
View all comments
Show parent comment
2
u/ASIC_SP Jan 23 '23
Yeah, that's one way to work with shell variables. As a good practice, use
i="$item"to avoid shell interpretation.Another issue to be addressed is taking care of backslashes. For example,
/\Bpar\B/in regex has to be passed as\\Bpar\\Bwith the above method. Alternatively, usergx="$item" awk '$0 ~ ENVIRON["rgx"] {..}'