[Copyright statement: reprinted. Please retain the Source: blog.csdn.net/gentleliu. Mail: shallnew at 163 dot com]
Since awk is often used in shell scripts, some variables in shell scripts must be passed to awk for use. This section describes how awk references the variable methods in shell.
To avoid the output of too many items on the screen, we should first treat the operated file as a line, as shown below:
# Catgroup_file3
Vboxusers: X: 984: Allen
1. Pass the variable before the file name.
Format: awk '{print var1, var2}' var1 = aaa var2 = BBB filename
#!/bin/sh shell_var="test"awk '{printvar}' var=$shell_var group_file3
Output result:
#./61_awk_var.shtest
The variable value must be placed before the file name. Otherwise, the variable value cannot be obtained. For example, if the script is written like this, the variable value is not output.
#!/bin/sh shell_var="test"awk '{print var}'group_file3 var=$shell_var
In fact, this method cannot use variables in begin, such as writing scripts like this:
#!/bin/sh shell_var="test" awk 'BEGIN{ print "begin output var:" var}{ print var}END{ print "end output var:" var} 'var=$shell_var group_file3
Output result:
#./64_awk_var.shbegin outputvar:testend outputvar:test
2. Use-V to pass variables.
Format: awk-V Var = $ shell_var '{print var}' filename
#!/bin/sh shell_var="test"awk -vvar=$shell_var '{print var}' group_file3
Try again whether the value can be used in begin:
#!/bin/sh shell_var="test" awk -vvar=$shell_var 'BEGIN{ print"begin output var:" var}{ print var}END{ print "end output var:" var} ' group_file3
Execution result:
#./63_awk_var.shbegin outputvar:testtestend outputvar:test
Variables passed in this method can be used in begin.
3. directly use shell variables.
Format: awk '{print "' $ shell_var '"}' filename. Note: Use double quotation marks and then single quotation marks.
#!/bin/sh var="test" awk 'BEGIN{ print "begin outputvar:" "'$var'"}{ print "'$var'"}END{ print "end outputvar:" "'$var'"} ' group_file3
Execution result:
# ./65_awk_var.sh begin output var:testtestend output var:test
Variable Transmission can not only pass custom variables, but also environment variables. The usage is similar to that of custom variables ..
Shell text filtering programming (7): Variable transfer of awk