直接举个例子来说明
<code lang="powershell">
$ cat datafile
northwest NW Joel Craig 3.0 .98 3
4
western WE Sharon Kelly 5.3 .97 5
23
southwest SW Chris Foster 2.7 .8 2
18
southern SO May Chin 5.1 .95 4
15
southeast SE Derek Johnson 4.0 .7 4
17
eastern EA Suan Beal 4.4 .84 5
20
northeast NE TJ Nichols 5.1 .94 3
13
north NO Val Shultz 4.5 .89 5
9
central CT Sheri Watson 5.7 .94 5
13
$ cat argvs.sc
# Testing command-line arguments with ARGV and ARGC using a for 1oop.
BEGIN{
for(i=0;
i<ARGC; i++){
printf("argv[%d]
is %s\n",i , ARGV[i]}
printf ("The
number of arguments, ARGC=%d\n",ARGC)
}
}
$ awk -f argvs.sc datafile
argv[O] is
nawk
argv[l] is
datafile
The number of arguments, ARGC=2
说明:BEGIN块中包含一个for循环,用于处理命令行参数。ARGC是参数的个数,
ARGV则是包含实际参数的数组。nawk不把选项当成参数。这个例子中的有效参数只有nawk命令和输入文件也datafile。
范例
$ awk ‘BEGIN{name=ARGV[1]};\
$0 ~ name {print $3, $4}‘ "Derek" datafile
awk: can t open Derek
source line number 1
$ awk ‘BEGIN {name=ARGV[1]; delete ARGV[1] };\
$0 ~ name {print $3, $4}‘ "Derek" datafile
Derek Johnson
说明
1.在BEGIN块中,名字"Derek"被赋给变量name。接下来的模式操作块中,awk试着将"Derek"作为输入文件打开,结果失败了。
2. 把"Derek"赋给变量name后,awk就把ARGV[1]删除了。进入模式操作块时,awk没有尝试将"Derek"作为输入文件打开,而是打开了文件datafile。
参考文章:http://www.linuxawk.com/jiaocheng/361.html