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

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

    I don't think the person is asking, "How do I split a string and get the length of the resulting array?" I think the command they provide is just an example of the situation where it arose. In particular, I think the person is asking 1) Why does length(array) provoke an error, and 2) How can I get the length of an array in awk?

    The answer to the first question is that the length function does not operate on arrays in POSIX standard awk, though it does in GNU awk (gawk) and a few other variations. The answer to the second question is (if we want a solution that works in all variations of awk) to do a linear scan.

    For example, a function like this:

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

    NOTE: The second parameter i warrants some explanation.

    The way you introduce local variables in awk is as extra function parameters and the convention is to indicate this by adding extra spaces before these parameters. This is discussed in the GNU Awk manual here.

提交回复
热议问题