awk中使用shell变量的方法有三种:
1、使用双引号quoting方法,就是在搜索的正则表达式的pattern中使用shell变量,这里可以直接使用双引号取得shell中的变量
printf "Enter search pattern: "
read pattern
awk "/$pattern/" '{ nmatches++ }
END { print nmatches, "found" }' /path/to/data
2、使用系统的环境变量:在awk中可以用ENVIRON数组引用系统的环境变量,例子如下
#!/bin/bash
id=1000
export id
awk '\
BEGIN {
print ENVIRON["id"];
}' test.txt
运行之后输出:1000
3、使用awk assign方法,-v参数
在awk的手册中,-v参数的描述如下:
-v var=val
--assign var=val
Assign the value val to the variable var, before execution of
the program begins.Such variable values are avail-able to
the BEGIN block of an AWK program.
-v参数后面可以给某一个变量赋值,这个就是连接shell和awk中程序的桥梁,这个应该是传递shell中的变量到awk中的正统方法,推荐使用这个方法。
使用例子如下:
#!/bin/bash
id=1000
awk -v awkId="$id" '\
BEGIN {
print awkId;
}' test.txt
输出:1000
参考文献:
http://yanwang.blog.51cto.com/1123232/383259
http://www.gnu.org/software/gawk/manual/html_node/Using-Shell-Variables.html
除注明转载的文章外,都是本人原创,转载时请加上原文链接并注明: 转载自品味生活
本文链接地址: awk使用shell中变量的方法
1、使用双引号quoting方法,就是在搜索的正则表达式的pattern中使用shell变量,这里可以直接使用双引号取得shell中的变量
printf "Enter search pattern: "
read pattern
awk "/$pattern/" '{ nmatches++ }
END { print nmatches, "found" }' /path/to/data
2、使用系统的环境变量:在awk中可以用ENVIRON数组引用系统的环境变量,例子如下
#!/bin/bash
id=1000
export id
awk '\
BEGIN {
print ENVIRON["id"];
}' test.txt
运行之后输出:1000
3、使用awk assign方法,-v参数
在awk的手册中,-v参数的描述如下:
-v var=val
--assign var=val
Assign the value val to the variable var, before execution of
the program begins.Such variable values are avail-able to
the BEGIN block of an AWK program.
-v参数后面可以给某一个变量赋值,这个就是连接shell和awk中程序的桥梁,这个应该是传递shell中的变量到awk中的正统方法,推荐使用这个方法。
使用例子如下:
#!/bin/bash
id=1000
awk -v awkId="$id" '\
BEGIN {
print awkId;
}' test.txt
输出:1000
参考文献:
http://yanwang.blog.51cto.com/1123232/383259
http://www.gnu.org/software/gawk/manual/html_node/Using-Shell-Variables.html
除注明转载的文章外,都是本人原创,转载时请加上原文链接并注明: 转载自品味生活
本文链接地址: awk使用shell中变量的方法