实例2:增加索引排序功能
[root@localhost ~] cat asort1.awk BEGIN { item[101]="HD Camcorder"; item[102]="Refrigerator";item[103]="MP3 Player"; item[104]="Tennis Racket"; item[105]="Laser Printer"; item[1001]="Tennis Ball"; item[55]="Laptop"; item["na"]="Not Available"; total = asort(item); for(i=1;i<=total;i++) #添加for循环控制索引输出的顺序 print "Index",i,"contains",item[i] } [root@localhost ~] awk -f asort1.awk Index 1 contains HD Camcorder Index 2 contains Laptop Index 3 contains Laser Printer Index 4 contains MP3 Player Index 5 contains Not Available Index 6 contains Refrigerator Index 7 contains Tennis Ball Index 8 contains Tennis Racket 七、用 asorti 为索引排序和以元素值排序相似,也可以取出所有索引值,排序,然后把他们保存在新数组中。
说明:
asorti 函数为索引值(不是元素值)排序,并且把排序后的元素值当做元素值保存。
如果使用 asorti(state)将会丢失原始元素值,即索引值变成了元素值。因此为了保险起见,通常给 asorti 传递两个参数,即 asorti(state,statebbr).这样一来,原始数组state 就不会被覆盖了。
实例1:
[root@localhost ~]# cat asorti.awk BEGIN { state["TX"]="Texas"; state["PA"]="Pennsylvania"; state["NV"]="Nevada"; state["CA"]="California"; state["AL"]="Alabama"; print "-------------- Function: asort -----------------" total = asort(state,statedesc); for(i=1;i<=total;i++) print "Index",i,"contains",statedesc[i]; print "-------------- Function: asorti -----------------" total = asorti(state,stateabbr); for(i=1;i<=total;i++) #索引按顺序输出也需要自行排序 print "Index",i,"contains",stateabbr[i]; } [root@localhost ~]# awk -f asorti.awk -------------- Function: asort ----------------- Index 1 contains Alabama Index 2 contains California Index 3 contains Nevada Index 4 contains Pennsylvania Index 5 contains Texas -------------- Function: asorti ----------------- Index 1 contains AL Index 2 contains CA Index 3 contains NV Index 4 contains PA Index 5 contains TX补充实例:利用数组删除重复行
[root@localhost ~]# cat alpha
a
a
a
b
c
b
d
d
e
e
f
f
f
f
g
[root@localhost ~]# awk '!a[$0]++' alpha
a
b
c
d
e
f
g
注解:
为何上面的命令将重复的行去掉了呢?原因如下:首先,当读入第一个字符a时,关联数组array的以a为索引的值为空,即array[a]=0,将此取反为1,逻辑上为真,则输出第一行,然后自相加为2。其次,当读入第二个值b时,同理可知为1,array也为1。当第二次读入a时,因为array[a]的值已经为2,(逻辑)取反之后为0,逻辑上是假,则不会输出,自相加最后为1。