Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
bash-3.00# cat iplogs.txt
180607 093423  133
180607 121234  153
190607 084849   44
190607 084859   12
200607 012312    13
210607 084849   34
210607 121435   32
210607 132423    167

bash-3.00# awk '{ip[$3]++;} END{for (var in ip)\
print var, "access", ip[var]," times"}' iplogs.txt access 2  times access 1  times access 3  times access 1  times access 1  time

The above output is unclear to me. How is $3 is incremented for every repeated value?

I expected that values assigned to array ip would be like:


and so on.

So I tried this, but the value of array ip[var] did not get printed.

bash-3.00# awk '{ip[$3]++;} END{for (var=0;var <= NR; var++)\
print var, ip[var]}' iplogs.txt
share|improve this question
up vote 3 down vote accepted

Associative arrays use strings as keys, not integer indices.* The key in this case is $3, which is an awk field variable corresponding to the third (3rd) field. In your sample input, this would be the 3rd column which contains strings that look like IPv4 addresses. In the expression ip[$3]++, if $3 is "", then ip[""] gets incremented. Since $3 is "" a total of two times in your sample input, ip[""] gets incremented two times. Since it started at 0 at the beginning as all uninitialized awk variables do, it ends up with a value of 2.

Your first example uses for (var in ip). This is the correct way to iterate over an array with unknown keys. Your second example uses for (var = 0; var <= NR; var++). However, as I said above, ip was created as an associative array whose keys are strings that look like IPv4 addresses, not integer indices. The elements ip[0], ip[1], ... do not exist because they were never assigned to (because at no point was $3 ever 0, 1, 2 ... ), which is why you get empty output ("").

* In awk, integer array indices are actually first converted to strings, so a[1] and a["1"] are the same element.

share|improve this answer
thanks @jw013 i got that but i am assuming ip[$3] gets incremented for each line that means value of ip[] should be 8. but how it gets counted to 2. – munish Nov 27 '12 at 15:58
is it incrementing for every repeated value? access 2 times – munish Nov 27 '12 at 15:59
@munish The value of $3 is not the same for every line, so ip[$3] is not the same for every line, so the same element is not being incremented for every line. – jw013 Nov 27 '12 at 16:02
hmmm..............................thanks – munish Nov 27 '12 at 16:05

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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