Linux awk 数组和循环(3)

1) 数组长度(length)

length(array) 获取数组长度, split 分割数组也返回数组长度,示例:

#!/bin/bash

awk 'BEGIN{
    info="it is  a  test";
    len = split(info, array, " ");
   
    print len, length(array);

print
    for(i in array){
        print i" = " array[i];
    }
}'

结果:

4    4

4 = test
1 = it
2 = is
3 = a

2) 数组排序(asort)

asort对数组array按照首字母进行排序,返回数组长度;

如果要得到数组原本顺序,需要使用数组下标依次访问;

for...in 输出关联数组的顺序是无序的,所以通过for…in 得到是无序的数组。如果需要得到有序数组,需要通过下标获得

示例:

#!/bin/bash

awk 'BEGIN{
    info="it is  a  test";
    len = split(info, array, " ");
   
    print len, length(array);

print "--- for in ---"
    for(i in array){
        print i" = " array[i];
    }

print "--- for ---"
    for(i=1; i<=len; i++){
        print i" = "array[i];
    }


    print
    print "--- asort ---"
    print "asort(array) = ", asort(array);
   

print
    print "--- for in ---"
    for(i in array){
        print i" = " array[i];
    }

print "--- for ---"
    for(i=1; i<=len; i++){
        print i" = "array[i];
    }
}'

结果:

4 4
--- for in ---
4 = test
1 = it
2 = is
3 = a
--- for ---
1 = it
2 = is
3 = a
4 = test

--- asort ---
asort(array) =  4

--- for in ---
4 = test
1 = a
2 = is
3 = it
--- for ---
1 = a
2 = is
3 = it
4 = test

3) 键值操作

a 查找键值(in)

awk 'BEGIN{array["a"]="aaa"; array["b"]="bbb"; if(array["c"]!="ccc"){print "no found";}; for(k in array){print k, array[k];}}'


结果:

no found
a aaa
b bbb
c


注: array[“c”]没有定义,但是循环时存在该键值,它的值为空。这是因为awk数组是关联数组,只要通过数组引用它的key,就会自动创建改序列


正确做法是用: in

awk 'BEGIN{array["a"]="aaa"; array["b"]="bbb"; if("c" in array){print "found";}else{print "not found"}; for(k in array){print k, array[k];}}'


结果:

not found
a aaa
b bbb


注: 没有引用array下标“c”,因此没有添加到数组中


b 删除键值(delete)

awk 'BEGIN{array["a"]="aaa"; array["b"]="bbb"; delete array["a"]; for(k in array){print k, array[k];}}'


结果: b bbb

linux

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/e2b61522f537341e6bde86697f6542b9.html