Awk uses shell variables, and shell obtains the variable values in awk.
09:36:28 | category:
Linux | font size subscription
Original article: http://renyongjie668.blog.163.com/blog/static/16005312011829102025222/
I think inLinuxLowerAwkIt is a good idea. It is very convenient to process some text files. In LinuxShellSo the variables between awk and shell are transferred to each other, and sometimes it is necessary. So let's simply summarize it.
Use variables in Shell in awk
I:
"'$ Var '"
In this way, you do not need to change the habit of using the awk program. It is a common method used by foreigners. For example:
Var ="Test"
Awk 'in in {print "'$ var '"}'
In this way, it is actually a constant that is changed from double brackets to single brackets and passed to awk.
If var contains spaces, shell should use the following as a grid character to avoid spaces:
Var = "this is a test"
Awk 'in in {print "'" $ Var "'"}'
Ii. '"$ Var "'
This method is similar to the previous one. If the variable contains spaces, it becomes '"$ Var" "' more reliable.
3. Use the environ ["Var"] form to obtain the value of the environment variable.
For example:
Var = "this is a test"; export var;
Awk 'in in {print environ ["Var"]}'
4. You can use the-V option of awk (if there are not many variables, I prefer this method)
For example:
Var = "this is a test"
Awk-V awk_var = "$ Var" 'In in {print awk_var }'
In this way, the system variable VAR is passed to the awk variable awk_var.
Awk transmits value to shell variable
The idea of "passing variables from awk to shell" is nothing more than outputting several shell commands with awk (SED/perl and so on), and then executing these commands with shell.
Eval $ (awk 'in in {print
"Var1 = 'str1'; var2 = 'str2 '"}')
Or eval
$ (Awk '{printf ("var1 = % s; var2 = % s; var3 = % s;", $1, $2, $3)} 'abc.txt)
Then you can use var1, var2, and other variables in the current shell.
Echo "var1 = $ var1 -----
Var2 = $ var2"
References:
Http://developer.51cto.com/art/200509/3781.htm
Http://www.ixpub.net/thread-1457438-1-1.html