awk -v 选项到底是什么意思 有点晕 -v var=val --assign=var=val

有-v的时候就没问题
[root@localhost test_3]# cat professor.db|awk -v RS="\n\n" '{gsub("\n","@") ;print}'
J Luo@Southeast University@Nanjing,China
Y Zhang@Victory University@Melbourne.Australia
D Hou@Beijing University@Beijing,China
B Liu@Shanghai Jiaotong University@Shanghai,China
C Lin@University of Toronto@Toronto,Canda

没有-v就这个错误
[root@localhost test_3]# cat professor.db|awk RS="\n\n" '{gsub("\n","@") ;print}'
awk: RS=\n\n
awk: ^ 反斜杠不是行的最后一个字符

说简单点就是,shell中的变量在awk程序中无法使用,因为在执行AWK时,是一个新的进程去处理的,因此就需要-v 来向awk程序中传参数了,你比如在shell程序中有一个变量a=15,你在awk程序中直接使用变量a是不行的,而你用awk -v b=a, 这样在AWK程序中就可以使用变量b了!也就相当于使用a了!
温馨提示:内容为网友见解,仅供参考
第1个回答  推荐于2016-08-25
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."
}
第2个回答  2011-05-10
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}'
第3个回答  2011-05-15
-v 是设置可以在awk 中使用的变量
相似回答