用awk进行文本处理,少不了就是它的数组处理。那么awk数组有那些特色,通常常见运算又会怎么样呢。咱们先看下如下的一些介绍,结合样例咱们会解说下它的不一样之处。在 awk 中数组叫作关联数组(associative arrays),因为下标记可以是数也可以是串。awk 中的数组没必要提早声明,也没必要声明大小。数组元素用 0 或空串来初始化,这依据上下文而定。好比:数组
1、定义方法函数
1:可以用数值做数组索引(下标)spa
Tarray[1]=“cheng mo” Tarray[2]=“800927”
2:可以用字符串做数组索引(下标)排序
Tarray[“first”]=“cheng ” Tarray[“last”]=”mo” Tarray[“birth”]=”800927”
使用中 print Tarray[1] 将获得”cheng mo” 而 print Tarray[2] 和 print[“birth”] 都将获得 ”800927” 。索引
2、数组相关函数ci
[chengmo@localhost ~]$ awk --version
GNU Awk 3.1.5字符串使用版本号是:3.1以上,不一样版本号如下函数不必定一样it
[chengmo@localhost ~]$ awk 'BEGIN{info="it is a test";lens=split(info,tA," ");print length(tA),lens;}'
4 4iolength返回字符串以及数组长度,split进行切割字符串为数组,也会返回切割获得数组长度。ast
(asort使用):
[chengmo@localhost ~]$ awk 'BEGIN{info="it is a test";split(info,tA," ");print asort(tA);}'
4asort对数组进行排序,返回数组长度。
[chengmo@localhost ~]$ awk 'BEGIN{info="it is a test";split(info,tA," ");for(k in tA){print k,tA[k];}}'
4 test
1 it
2 is
3 a
for…in 输出,因为数组是关联数组,默认是无序的。因此经过for…in 获得是无序的数组。假设需要获得有序数组,需要经过下标得到。
[chengmo@localhost ~]$ awk 'BEGIN{info="it is a test";tlen=split(info,tA," ");for(k=1;k<=tlen;k++){print k,tA[k];}}'
1 it
2 is
3 a
4 test注意:数组下标是从1開始,与c数组不同。
一个错误的推断方法:
[chengmo@localhost ~]$ awk 'BEGIN{tB["a"]="a1";tB["b"]="b1";if(tB["c"]!="1"){print "no found";};for(k in tB){print k,tB[k];}}'
no found
a a1
b b1
c
以上出现奇怪问题,tB[“c”]未定义,但是循环时候,发现已经存在该键值,它的值为空,这里需要注意,awk数组是关联数组,仅仅要经过数组引用它的key,就会本身主动建立改序列.
正确推断方法:
[chengmo@localhost ~]$ awk 'BEGIN{tB["a"]="a1";tB["b"]="b1";if( "c" in tB){print "ok";};for(k in tB){print k,tB[k];}}'
a a1
b b1if(key in array) 经过这个方法推断数组中是否包括”key”键值。
删除键值:
[chengmo@localhost ~]$ awk 'BEGIN{tB["a"]="a1";tB["b"]="b1";delete tB["a"];for(k in tB){print k,tB[k];}}'
b b1
delete array[key]可以删除,相应数组key的,序列值。
3、二维数组使用(多维数组使用)
awk的多维数组在本质上是一维数组,更确切一点,awk在存储上并不支持多维数组。awk提供了逻辑上模拟二维数组的訪问方式。例 如,array[2,4] = 1这种訪问是赞成的。awk使用一个特殊的字符串SUBSEP (\034)做为切割字段,在上面的样例中,关联数组array存储的键值其实是2\0344。
类似一维数组的成员測试,多维数组可以使用 if ( (i,j) in array)这种语法,但是下标必须放置在圆括号里。
类似一维数组的循环訪问,多维数组使用 for ( item in array )这种语法遍历数组。与一维数组不一样的是,多维数组必须使用split()函数来訪问单独的下标份量。split ( item, subscr, SUBSEP)
[chengmo@localhost ~]$ awk 'BEGIN{
for(i=1;i<=9;i++)
{
for(j=1;j<=9;j++)
{
tarr[i,j]=i*j;
print i,"*",j,"=",tarr[i,j];
}
}
}'
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
1 * 6 = 6……
可以经过array[k,k2]引用得到数组内容.
方法二:
[chengmo@localhost ~]$ awk 'BEGIN{
for(i=1;i<=9;i++)
{
for(j=1;j<=9;j++)
{
tarr[i,j]=i*j;
}
}
for(m in tarr)
{
split(m,tarr2,SUBSEP);
print tarr2[1],"*",tarr2[2],"=",tarr[m];
}
}'
以上是awk对数组的处理相关,但愿对你们实用