How can I get the length of an array in awk?

前端 未结 8 1134
时光取名叫无心
时光取名叫无心 2020-12-03 04:22

This command

echo \"hello world\" | awk \'{split($0, array, \" \")} END{print length(array) }\'

does not work for me and gives this error m

8条回答
  •  庸人自扰
    2020-12-03 04:48

    Mr. Ventimiglia's function requires a little adjustment to do the work (see the semicolon in for statement):

    function alen(a, i) {
        for(i in a);
        return i
    }
    

    But don't work all the cases or times. That is because the manner that awk store and "see" the indexes of the arrays: they are associative and no necessarily contiguous (like C.) So, i does not return the "last" element.

    To resolve it, you need to count:

    function alen(a, i, k) {
        k = 0
        for(i in a) k++
        return k
    }
    

    And, in this manner, take care other index types of "unidimensional" arrays, where the index maybe an string. Please see: http://docstore.mik.ua/orelly/unix/sedawk/ch08_04.htm. For "multidimensional" and arbitrary arrays, see http://www.gnu.org/software/gawk/manual/html_node/Walking-Arrays.html#Walking-Arrays.

提交回复
热议问题