How to insert shell variable inside awk command
If you want to /grep/
with your variable, you have 2 choices :
interface=eth0awk "/$interface/{print}"
or
awk -v interface=eth0 '$0 ~ interface{print}'
See http://www.gnu.org/software/gawk/manual/gawk.html#Using-Shell-Variables
it's like I thought,
awk
substitutes variables properly, but between//
, inside regex ( orawk
regex, depending on someawk
parameter AFAIR),awk
variable cannot be used for substitution
I had no issue grepping with variable inside an awk
program (for simple regexp cases):
sawk1='repo\s+module2' sawk2='@project2\s+=\s+module2$'awk "/${sawk1}/,/${sawk2}/"'{print}' aFile
(Here the /xxx/,/yyy/
displays everything between xxx
and yyy
)
(Note the double-quoted "/${sawk1}/,/${sawk2}/"
, followed by the single-quoted '{print}'
)
This works just fine, and comes from "awk: Using Shell Variables in Programs":
A common method is to use shell quoting to substitute the variable’s value into the program inside the script.
For example, consider the following program:
printf "Enter search pattern: "read patternawk "/$pattern/ "'{ nmatches++ } END { print nmatches, "found" }' /path/to/data
The awk program consists of two pieces of quoted text that are concatenated together to form the program.
- The first part is double-quoted, which allows substitution of the pattern shell variable inside the quotes.
- The second part is single-quoted.
It does add the caveat though:
Variable substitution via quoting works, but can potentially be messy.
It requires a good understanding of the shell’s quoting rules (see Quoting), and it’s often difficult to correctly match up the quotes when reading the program.