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

前端 未结 8 1128
时光取名叫无心
时光取名叫无心 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:34

    In gawk you can use the function length():

    $ gawk 'BEGIN{a[1]=1; a[2]=2; a[23]=45; print length(a)}'
    3
    
    $ gawk 'BEGIN{a[1]=1; a[2]=2; print length(a); a[23]=45; print length(a)}'
    2
    3
    

    From The GNU Awk user's guide:

    With gawk and several other awk implementations, when given an array argument, the length() function returns the number of elements in the array. (c.e.) This is less useful than it might seem at first, as the array is not guaranteed to be indexed from one to the number of elements in it. If --lint is provided on the command line (see Options), gawk warns that passing an array argument is not portable. If --posix is supplied, using an array argument is a fatal error (see Arrays).

提交回复
热议问题