2

I am baffled at the response of these scripts.

Trial 1:

awk '{line_arr[$0] } END {for (line in line_arr) print line}' text_file

Output:

1
2
3
4

Trial 2:

awk '{line_arr[$0] } END {for (line in line_arr) print line}' text_file

Output:

is some text.
Hello. Here
Lots of random
text.

File content:

$ cat text_file
Hello. Here
is some text.
Lots of random
text.

Why is the index of the array storing as an actual value?

Why is the second trial out of order?

  • I am not sure why I would put line as the index. line is just a iteration of array from the for loop. Someone else mentioned this to me and I tried it. It was just printing 4 blank lines, nothing else. I am confused by the array sytax mostly. The array order was unkown to me. Thanks. – Michael Bruce Aug 29 '16 at 4:03
  • What's your awk version? – cuonglm Aug 29 '16 at 4:09
  • What is your output in the first case? Is it output line number or the line content? – cuonglm Aug 29 '16 at 4:11
  • awk seems to be gawk 4.1.3-2 – Michael Bruce Aug 29 '16 at 4:13
  • It is line number. On another file it is also a climbing pattern. – Michael Bruce Aug 29 '16 at 4:14
3

With this rare syntax, awk stores your lines in an Associative Array. Thus it has no defined order. You reached an undefined behavior.

Here is how to get convinced: print the line number from the associative array itself:

$ awk '{line_arr[$0]=NR } END \
       {for (line in line_arr) print line_arr[line]"=>"line } \
      ' text_file

3=>Lots of random
1=>Hello. Here
4=>text.
2=>is some text.

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.