Shell – Using variable with awk -v in a shell script

awkshell-script

I am modifying/re-writing some of the scripts written by former employees of my company and in one of the shell scripts I found the following line.

b=`benchmark=30;grep "Waiting for timer" wk.txt | awk -vbenchmark=$benchmark '$6 > benchmark' | wc -l`

But my bad, I couldn't figure out what the above line is trying to do. I am confused about the usage of 'benchmark' variable here. I created a dummy 'wk.txt' file with the following values and the when echoed, variable $b got the value 1 (which is just a line count of the output of the grep+awk command.

[sreeraj@server ~]$ cat wk.txt
24  here  above the Waiting for timer 37 make sure

Could someone explain what the script author is trying to do with the $benchmark?

awk man page says the below for -v, but I am not I understood what it does.

-v var=val
--assign var=val
          Assign the value val to the variable var, before execution of the program begins.   Such  variable  values  are
          available to the BEGIN block of an AWK program.

Best Answer

If you do:

awk -v benchmark=30 '...'

That is the same as:

awk 'BEGIN{ benchmark = 30 } ... '

This is used to set an initial value for that variable.

Though I don't see why the author does:

benchmark=30; ... | awk -v benchmark=$benchmark ..

They might as well do:

... | awk -v benchmark=30 ..
Related Question