gawk: Using Shell Variables
1
1 7.2 Using Shell Variables in Programs
1 =====================================
1
1 'awk' programs are often used as components in larger programs written
1 in shell. For example, it is very common to use a shell variable to
1 hold a pattern that the 'awk' program searches for. There are two ways
1 to get the value of the shell variable into the body of the 'awk'
1 program.
1
1 A common method is to use shell quoting to substitute the variable's
1 value into the program inside the script. For example, consider the
1 following program:
1
1 printf "Enter search pattern: "
1 read pattern
1 awk "/$pattern/ "'{ nmatches++ }
1 END { print nmatches, "found" }' /path/to/data
1
1 The 'awk' program consists of two pieces of quoted text that are
1 concatenated together to form the program. The first part is
1 double-quoted, which allows substitution of the 'pattern' shell variable
1 inside the quotes. The second part is single-quoted.
1
1 Variable substitution via quoting works, but can potentially be
1 messy. It requires a good understanding of the shell's quoting rules
1 (⇒Quoting), and it's often difficult to correctly match up the
1 quotes when reading the program.
1
1 Assignment Options::) to assign the shell variable's value to an 'awk'
11 variable. Then use dynamic regexps to match the pattern (⇒Computed
Regexps). The following shows how to redo the previous example using
1 this technique:
1
1 printf "Enter search pattern: "
1 read pattern
1 awk -v pat="$pattern" '$0 ~ pat { nmatches++ }
1 END { print nmatches, "found" }' /path/to/data
1
1 Now, the 'awk' program is just one single-quoted string. The assignment
1 '-v pat="$pattern"' still requires double quotes, in case there is
1 whitespace in the value of '$pattern'. The 'awk' variable 'pat' could
1 be named 'pattern' too, but that would be more confusing. Using a
1 variable also provides more flexibility, as the variable can be used
1 anywhere inside the program--for printing, as an array subscript, or for
1 any other use--without requiring the quoting tricks at every point in
1 the program.
1