说简单点就是,shell中的变量在awk程序中无法使用,因为在执行AWK时,是一个新的进程去处理的,因此就需要-v 来向awk程序中传参数了,你比如在shell程序中有一个变量a=15,你在awk程序中直接使用变量a是不行的,而你用awk -v b=a, 这样在AWK程序中就可以使用变量b了!也就相当于使用a了!
1、调用awk
awk [options] -f progfile [--] file ...
awk [options] [--] 'program' file ...
2、命令行选项
-F fs
--field-separator fs
设置字段分隔符,如打印用户:
awk -F : '{print $1}' /etc/passwd
-f source-file
--file source-file
从文件读取程序,如:awk -f file /etc/passwd
file内容为:
#!/bin/awk -f
BEGIN {FS=":"}
{print $1}
-v var=val
--assign var=val
设置var的值为val,如:awk -v foo=hello -v bar=world 'BEGIN {print foo,bar}'
3、包含其它文件到awk程序
@include "test1"
BEGIN {
print "This is script test2."
}
man awk
看帮助文档
-v var=val
--assign var=val
Assign the value val to the variable var, before execution of the program begins. Such variable values are available to the BEGIN block of an AWK program.
等同于这样:
cat professor.db|awk ‘BEGIN{RS="\n\n"} {gsub("\n","@") ;print}'
-v 是设置可以在awk 中使用的变量