ARGV awk可以从内置数组ARGV中得到命令行参数,其中包括命令awk。但所有传递给awk的选项都不在其中。ARGV数组的下标从0开始。
ARGC ARGC是一个包含命令行参数个数的内置变量。
范例
$
cat argvs
# Scriptname:argvs
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 datafile
argv [ 0 ] is awk
argv [ 1 ] is datafile
The number of arguments , ARGC = 2
# Scriptname:argvs
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 datafile
argv [ 0 ] is awk
argv [ 1 ] is datafile
The number of arguments , ARGC = 2
说明
for循环先将i设为0,然后测试它是否小于命令行参数的个数(ARGC) ,再用printf函数依次显示出每个参数。所有参数处理完之后,最后那条printf 语句用来输出参数的个数ARGC。这个例子说明awk并不把命令行选项视为参数。
范例
$ awk
-f argvs datafile
"Peter Pan"
12
argv [ 0 ] is awk
argv [ 1 ] is datafile
argv [ 2 ] is Peter Plan
argv [ 3 ] is 12
The number of arguments ,ARGV = 4
argv [ 0 ] is awk
argv [ 1 ] is datafile
argv [ 2 ] is Peter Plan
argv [ 3 ] is 12
The number of arguments ,ARGV = 4
说明:和上个例子一样,打印出所有参数。nawk命令被当成第一个参数,而-f选项和脚本文件名(即argvs)则被排除在外。
范例
$
cat datafile5
Tom Jones: 123:03 / 14 / 56
Peter Pan: 456:06 / 22 / 58
Joe Blow: 145: 12 / 12 / 78
Santa Ana: 234:02 /03 / 66
Ariel Jones: 987: 11 / 12 / 66
$ cat arging. sc
# Scriptname:arging.sc
BEGIN {FS = ":";name =ARGV [ 2 ]
print "ARGV[2] is "ARGV [ 2 ]
}
$1 ~ name {print $0 }
$ awk -f arging. sc datafile5 "Peter Pan"
ARGV [ 2 ] is Peter Pan
Peter Pan: 456:06 / 22 / 58
nawk: can 't open Peter Pan
input record number 5, file Peter Pan
source 1ine number 2
Tom Jones: 123:03 / 14 / 56
Peter Pan: 456:06 / 22 / 58
Joe Blow: 145: 12 / 12 / 78
Santa Ana: 234:02 /03 / 66
Ariel Jones: 987: 11 / 12 / 66
$ cat arging. sc
# Scriptname:arging.sc
BEGIN {FS = ":";name =ARGV [ 2 ]
print "ARGV[2] is "ARGV [ 2 ]
}
$1 ~ name {print $0 }
$ awk -f arging. sc datafile5 "Peter Pan"
ARGV [ 2 ] is Peter Pan
Peter Pan: 456:06 / 22 / 58
nawk: can 't open Peter Pan
input record number 5, file Peter Pan
source 1ine number 2
说明:
1.在BEGIN块中,ARGV[2]的值,即Peter Pan,被赋给变量name。
2.Peter Pan被打印出来了,但是,处理完datafile并将其关闭后,awk试图把Peter Pan作为输入文件打开。awk把参数都作为输入文件。
范例
$
cat arging2.
sc
BEGIN {FS = ";";name =ARGV [ 2 ]
print "ARGV[2] is "ARGV [ 2 ]
delete ARGV [ 2 ]
}
$1 ~ name {print $0 }
$ awk -f arging2. sc datafile "Peter Pan"
ARGV [ 2 ] is Peter Pan
Peter Pan: 456:06 / 22 / 58
BEGIN {FS = ";";name =ARGV [ 2 ]
print "ARGV[2] is "ARGV [ 2 ]
delete ARGV [ 2 ]
}
$1 ~ name {print $0 }
$ awk -f arging2. sc datafile "Peter Pan"
ARGV [ 2 ] is Peter Pan
Peter Pan: 456:06 / 22 / 58
说明:awk把ARGV数组的元素作为输入文件。且awk用完一个参数就将它左移,接着处理下一个,直到ARGV数组变空。如果某个参数使用后立刻被删除,那么这个参数就不会被当作下一个输入文件来处理。
参考资料:http://www.linuxawk.com/jiaocheng/295.html