In awk, it's not possible to use shell variables directly.
The AWK-V option allows awk to use the shell variable
Time=60
Awk-v time= "$TIME" ' begin{fs= ' | '} {if ($7>time) print $} '
Note: In awk, time cannot be added to the $ symbol.
Online said the following methods are feasible:
One: "' $var '"
In this way, you don't have to change the habit of using the AWK program, which is commonly used by foreigners. such as:
var= "Test"
awk ' begin{print ' $var ' "} '
This notation is actually a constant that is double-parenthesis into parentheses, passed to awk.
If the var contains spaces, for the shell not to use the space as a separator, it should be used as follows:
Var= "This is a test"
awk ' Begin{print ' "$var" ' "} '
Two: ' $var '
This is similar to the previous one. If the variable contains spaces, it becomes ' "" $var "" is more reliable.
Three. "Change to", "$var", which encloses the awk program
Such as:
$var = "This is a test"
awk ' Begin{print ' $var "}"
This is because in "" the $ is a special character, while in the ' $ ' is the ordinary character.
Four: Export variable, using environ["var" form,
Such as:
$var = "This is a test"; Export $var
awk ' Begin{print environ["var"]} '
V: Of course you can also use the-v option
Such as:
$var = "This is a test"
Awk-v nvar= "$var" ' {Print Nvar} '
This defines the system variable as the awk variable.
--------------------------------------------------------------------------------------------------------------- -----------------------------------------------------------------
Awk reads variables from the shell
Features can be implemented using the-V option
$b =1
$cat F
Apple
$awk-V var= $b ' {print var, $var} ' F
1 apple
In addition to using the-v option, you can use ' $variable ' to pass variables from the shell to awk (note: This is a single quote)
$awk ' {print $b, ' $b '} ' F
Apple 1
If the variable contains spaces, it becomes ' "" $var "" is more reliable.
As to whether there is any way to pass the variables in awk to the shell, this is the question I understand. The shell calls awk to actually fork a child process out, and the child process cannot pass the variable to the parent process unless redirected (including pipelines)
$a =$ (awk ' {print $b, ' $b '} ' F)
$echo $a
Apple 1
Attached 1:http://bbs.chinaunix.net/thread-1381166-1-1.html
Attached 2:http://www.cnblogs.com/mydomain/archive/2012/09/24/2699467.html
Using shell variables in awk