Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 422
softghost Avatar asked Feb 19 '12 18:02

softghost


People also ask

What is array length ()?

length is a property of arrays in JavaScript that returns or sets the number of elements in a given array. The length property of an array can be returned like so. let desserts = ["Cake", "Pie", "Brownies"]; console. log(desserts.

How do I find the length of a string in awk?

awk length(string) Function: The length() function calculates the length of a string. Explanation: Length of the string also includes spaces. 3. awk substr(s, p, n) Function: The length() function is used to extract substring function from a string.

How do you declare the length of an array?

var-name = new type [size]; Here, type specifies the type of data being allocated, size determines the number of elements in the array, and var-name is the name of the array variable that is linked to the array. To use new to allocate an array, you must specify the type and number of elements to allocate.


1 Answers

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 
like image 176
shellter Avatar answered Sep 28 '22 01:09

shellter