awk数组操做介绍

用awk进行文本处理,少不了就是它的数组处理。那么awk数组有那些特色,通常常见运算又会怎么样呢。咱们先看下下面的一些介绍,结合例子咱们会讲解下它的不一样之处。在 awk 中数组叫作关联数组(associative arrays),由于下标记能够是数也能够是串。awk 中的数组没必要提早声明,也没必要声明大小。数组元素用 0 或空串来初始化,这根据上下文而定。例如:web

1、定义方法数组

 

1:能够用数值做数组索引(下标)ide

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、数组相关函数spa

 

[liu@weblogic ~]$ awk --versionorm

GNU Awk 3.1.7blog

Copyright (C) 1989, 1991-2009 Free Software Foundation.排序



  • 获得数组长度(length方法使用索引

[chengmo@localhost ~]$ awk 'BEGIN{info="it is a test";lens=split(info,tA," ");print length(tA),lens;}'
4 4

length返回字符串以及数组长度,split进行分割字符串为数组,也会返回分割获得数组长度。

 

(asort使用):

[chengmo@localhost ~]$ awk 'BEGIN{info="it is a test";split(info,tA," ");print asort(tA);}'
4

asort对数组进行排序,返回数组长度。

  • 输出数组内容(无序,有序输出):

[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 b1

if(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对数组的处理相关,但愿对你们有用。

相关文章
相关标签/搜索