awk 数组学习。
awk是Linux一个必不可少的文本处理工具,其编程简单,功能强大。其中awk处理文本的几块比较常用:1、行分隔 ; 2、正则表达式匹配 ;3、字符串处理 ; 4、awk数组
接下来主要介绍一下awk数组的相关内容。
awk数组特点:
(1)、是一种关联数组(Associative Arrays),下表可以是 数字 也可以 是字符串,
(2)、数组名 和 元素 无需提前声明,
(3)、无需指定数组元素的个数
所以awk的数组使用非常灵活。
1、建立awk数组
[python] view plaincopy
- awk ’BEGIN{ {a["你好"]=1} for(item in a) {print item;print a[item]}}’
awk 定义一个关联数组,并输出 关联数组的 key 值 和 value; key值可以通过for( item in a )来获取, value 通过 a[item]来获取;
[python] view plaincopy
- awk ’BEGIN{ {a["你好"]=1;a["helloworld"] = 3} {print length(a)}}’
获取数组长度的函数 length() ;
2、读取awk数组中的数据的值
[python] view plaincopy
- awk ’BEGIN{{a[1] =”x”;a[2]=”b”;a[3]=”c”} for(item in a){printf(“%d is %s\n”,item,a[item])}}’
ans:
[python] view plaincopy
- 1 is x
- 2 is b
- 3 is c
使用 for( item in array) 遍历, 这种遍历获取到的数据时随机的。
[python] view plaincopy
- awk ’BEGIN{{a[1] =”x”;a[2]=”b”;a[3]=”c”} for( i = 0;i<length(a);i++){printf(“%d is %s\n”,i,a[i])}}’
ans:
[python] view plaincopy
- 0 is
- 1 is x
- 2 is b
- 3 is c
使用 for(i; i< len ; i++) 遍历
3、多维数组, array[index1,index2....] SUBSEP是数组的下标分隔符,默认为 “\034″。可以事先设定 SUBSEP,也可以在SUBSEP的位置输入分隔符
[python] view plaincopy
- awk ’BEGIN{ {SUBSEP=”|”;a["x","y"]=”hello world”;} for(item in a){print item ;print a[item]}}’
ans:
[python] view plaincopy
- x|y
- hello world
上述是通过SUBSEP设置分隔符,也可以直接在分隔符位置输入分隔符。
[python] view plaincopy
- [root@SJSWT46-145 awkFile]# awk ’BEGIN{ {a["x"",""y"]=”hello world”;} for(item
ans:
[python] view plaincopy
- x,y
- hello world
4、删除数组或者删除数组的元素
[python] view plaincopy
- awk ’BEGIN{ {a["x"",""y"]=”hello world”;} for(item in a){print item ;print a[item]} {print ”—-delete array—”}{delete a} for(item in a){print item} }’
ans:
[python] view plaincopy
- x,y
- hello world
- —-delete array—
删除数组中的某一个元素:
[python] view plaincopy
- awk ’BEGIN{{a[1] =”x”;a[2]=”b”;a[3]=”c”} for( i = 0;i<length(a);i++){printf(“%d is %s\n”,i,a[i])} {print ”*** del ***”} {delete a[2]} for( i = 0;i<length(a);i++){printf(“%d is %s\n”,i,a[i])}}’
ans:
[python] view plaincopy
- 0 is
- 1 is x
- 2 is b
- 3 is c
- *** del ***
- 0 is
- 1 is x
- 2 is
- 3 is c
5、数组的排序, awk提供asort函数实现对数组的值进行排序,注意:排序之后数组的下标改将从1开始 ; 更高的版本提供 关联数组下标的排序。
[python] view plaincopy
- <span style=”color:#ff0000;”> </span>awk ’BEGIN{{a[0] = ”z” ;a[1] =”x”;a[2]=”b”;a[3]=”c”} for( i = 0;i<length(a);i++){printf(“%d is %s\n”,i,a[i])} {asort(a)} {print ”*********”} for( i = 0;i<length(a);i++){printf(“%d is %s\n”,i,a[i])}}’
ans:
[python] view plaincopy
- 0 is z
- 1 is x
- 2 is b
- 3 is c
- *********
- 0 is
- 1 is b
- 2 is c
- 3 is x
- 4 is z