awk 数组

– Start
awk 不区分索引数组和关联数组,也就是说,下标可以是数字或任何字符串。

#! /usr/bin/awk -f

BEGIN {
    # 定义索引数组
    names[0]="Shang Bo";
    names[2]="Li Si";
    names[1]="Zhang San";

    # 定义关联数组
    country_code_name_map["CN"]="CHINA";
    country_code_name_map["US"]="UNITED STATES";
    country_code_name_map["JP"]="JAPAN";

    # 通过 split 定义数组
    str1="a,b,c,d";
    split(str1, alphabet, ",");

    # 对数组排序
    asort(names);
    for (key in names) { # 迭代数组
        printf("names[%s]=%s\n", key, names[key]);
    }

    # 抽出并排序关联数组下标
    asorti(country_code_name_map, country_codes);
    for (key in country_codes) {
        printf("country_codes[%s]=%s\n", key, country_codes[key]);
    }

    # 删除数组元素
    delete names[0];
    if (0 in names) { #判断下标是否存在
        print "index 0 exists";
    }

    # 删除数组
    delete alphabet;
    for (key in alphabet) {
        printf("alphabet[%s]=%s\n", key, alphabet[key]);
    }

    # 定义多维数组
    for (i = 1; i <= 9; i++) {
        for (j = 1; j <= 9; j++) {
            table[i, j] = i * j;
        }
    }

    # 迭代多维数组
    for (key in table) {
        printf("table[%s]=%s\n", key, table[key]);
    }

    # 迭代多维数组
    for (key in table) {
        split(key, indexs, SUBSEP); # SUBSEP 是一个内置变量,多维数组下标分隔符
        printf("table[%s, %s]=%s\n", indexs[1], indexs[2], table[indexs[1], indexs[2]]);
    }
};

{};
END {};

– 更多参见:awk 精萃
– 声 明:转载请注明出处
– Last Updated on 2015-10-28
– Written by ShangBo on 2015-10-27
– End

你可能感兴趣的:(Linux)