46

In my understanding, awk array is something like python dict.

So I write down the code bellow to explore it:

awk '{my_dict[$1] = $2} END { print my_dict}' zen

And I got: awk: can't read value of my_dict; it's an array name.

As the first column isn`t a number, how could I read the total content of the array or traverse it?

64

You can loop over the array's keys and extract the corresponding values:

awk '{my_dict[$1] = $2} END { for (key in my_dict) { print my_dict[key] } }' zen

To get output similar to that you'd get with a Python dictionary, you can print the key as well:

awk '{my_dict[$1] = $2} END { for (key in my_dict) { print key ": " my_dict[key] } }' zen

This works regardless of the key type.

15

That would loop through the array:

END { for (i in my_dict) print my_dict[i] }

i is the index.

9

Array in awk is not first class object like dictionary in Python. In awk, array name without subscript can only use in two context:

  • A parameter in a function definition or function call.
  • Name token after keyword in.

In other context, awk will raise an error.

You need a for loop to iterate and print content of an array:

$ echo 1 2 | awk '{my_dict[$1] = $2};END {for(i in my_dict) print my_dict[i]}'
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.