awk Passing variables
Passing variables to AWK
AWK has the -v
option which is used to assign values to variables. For the next program, we have the general file:
$cat general
The French nation, oppressed, degraded during many centuries
by the most insolent despotism, has finally awakened to a
consciousness of its rights and of the power to which its
destinies summon it.
mygrep.awk
{
for (i=1; i<=NF; i++) {
field = $i
if (field ~ word) {
c = index($0, field)
print NR "," c, $0
next
}
}
}
The example simulates the grep
utility. It finds the provided word and prints its line and the its starting index. (The program finds only the first occurrence of the word.) The word
variable is passed to the program using the -v
option.
$ awk -f mygrep.awk -v word=the general
2,4 by the most insolent despotism, has finally awakened to a
3,36 consciousness of its rights and of the power to which its
We have looked for the “the” word in the text file.