Invoking awk in a shell script is very natural and simple, and if you need to invoke the shell script/command, you need to use the system () function, which is written as System ("sh my.sh" $var) if you need to pass the variable to the called Shell. Note that there is a space before the second quotation mark.
Awk calls the shell and passes the variable to the shell, and looking at the demo below, it's clear:
The code is as follows |
Copy Code |
jay@jay-linux:/tmp$ Cat Data.txt Var1 var2 1 2 jay@jay-linux:/tmp$ Cat my.sh #!/bin/bash echo $ jay@jay-linux:/tmp$ awk ' {System ("sh my.sh" $)} ' Data.txt Var2 2 |
method of variable transfer between awk and Shell
I think awk is a good thing to do with Linux, and it's very handy to work with some text files. And in Linux, often with the shell, so the variables between awk and the shell pass each other, sometimes it is necessary, so a simple summary.
using variables in the shell in awk
one: "' $var '"
This type of writing does not need to change the habit of ' surround the awk procedure, which is commonly used by foreigners. such as:
var= "Test"
awk ' begin{print ' ' $var ' "} '
This notation is actually a constant of double brackets into a single bracket, passed to awk.
If the Var contains a space, the shell does not use a 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 ' ' more reliable.
Three: Export variable, use environ["var" form, get the value of environment variable
For example:
Var= "This is a test"; Export var;
awk ' Begin{print environ[' var ']} '
Four: You can use the-v option for awk (if the number of variables is not much, individuals prefer to do this)
For example:
var= "This is a test"
Awk-v awk_var= $var ' BEGIN {print Awk_var} '
to pass the system variable var to the awk variable Awk_var.
Awk passes values to the shell variable
By using awk to pass variables to the shell, the idea is to use awk (Sed/perl, and so on) to output several shell commands, and then use the shell to execute the commands.
Eval $ (awk ' begin{print "var1= ' str1′;var2= ' str2′"} ')
or eval $ (awk ' {printf) ("var1=%s; var2=%s; var3=%s, $1,$2,$3)} ' abc.txt '
can then use variables such as var1,var2 in the current shell.
Echo "var1= $var 1-–var2= $var 2″