awk

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


This command

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

does not work for me and gives this error message

awk: line 1: illegal reference to array array

Why?


Solution

  • When you split an array, the number of elements is returned, so you can say:

    echo "hello world" | awk '{n=split($0, array, " ")} END{print n }'
    # ------------------------^^^--------------------------------^^
    

    Output is:

    2