awk and Shell pass value to each other

Source: Internet
Author: User
Tags eval
Using variables from the shell in awk
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: 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 awk's-v option (if the number of variables is not many, the individual favors this type of writing)
For example:
Var= "This is a test"
Awk-v awk_var= "$var" ' BEGIN {print Awk_var} '
This then passes the system variable var to the awk variable Awk_var.

awk passing values to shell variables
The idea of passing a variable from awk to the shell is simply to output several shell commands using awk (Sed/perl, and so on), 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)
Variables such as var1,var2 can then be used in the current shell.
echo "var1= $var 1-----var2= $var 2"
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.