Maxim Shoustin
Maxim Shoustin

Reputation: 77910

How to increment array dynamically with 'awk'?

I have file that contains list of IPs:

1.1.1.1
2.2.2.2
3.3.3.3
5.5.5.5
1.1.1.1
5.5.5.5

I want to create file that prints list of counters of above mentioned IPs like:

1.1.1.1: 2
2.2.2.2: 1
3.3.3.3: 1
5.5.5.5: 2

Where 2,1,1,2 are counters.

I started to write script that work for final count IPs and known count but don't know how to continue

 ./ff.sh file_with_IPs.txt

script

#!/bin/sh

file=$1

awk  '
BEGIN {
    for(x=0; x<4; ++x)
        count[x] = 0;

 ip[0] = "1.1.1.1";
 ip[1] = "2.2.2.2";
 ip[2] = "3.3.3.3";
 ip[3] = "5.5.5.5";    
}
{
    if($1==ip[0]){
       count[0] += 1;
     } else if($1==ip[1]){
       count[1] += 1;
     }else if($1==ip[2]){
       count[2] += 1;
     }else if($1==ip[3]){
       count[3] += 1;
     }
}
END {
    for(x=0; x<4; ++x) {
       print ip[x] ": " count[x]
    }
}
' $file > newfile.txt

The main problem that I don't know how many IPs stored in file and how they look like.

So I need to increment array ip each time when awk catch new IP.

Upvotes: 1

Views: 3110

Answers (2)

fedorqui
fedorqui

Reputation: 290115

I think it is quite easier with sort -u, but with awk this can do it:

awk '{a[$0]++; next}END {for (i in a) print i": "a[i]}' file_with_IPs.txt

Output:

1.1.1.1: 2
3.3.3.3: 1
5.5.5.5: 2
2.2.2.2: 1

(with a little help of this tutorial that sudo_O recommended me)

Upvotes: 5

Zsolt Botykai
Zsolt Botykai

Reputation: 51653

You can use uniq for that task, like:

sort IPFILE | uniq -c

(Note, that this prints the occurrences in front of the IP.)

Or with awk (if there are only IP addresses on the lines):

awk '{ips[$0]++} END { for (k in ips) { print k, ips[k] } }' IPFILE

(Note, this prints the IP addresses unordered, but you can do it with awk, read the docs, for asort, asorti, or simply append a sort after a pipe. )

Upvotes: 3

Related Questions