Abhishek
Abhishek

Reputation: 325

How do I count number of instances of an output in awk?

TL;DR

The idea is :

awk '{
    IP[$1]++;
  }
  END {
    for(var in IP) 
      print IP[var]
  }
}' getline < sockstat | awk '{print $2 "@" $3}' | grep -v '^PROCESS@PID'

I want to count the number of instance of every block in the output from -> sockstat | awk '{print $2 "@" $3}' | grep -v '^PROCESS@PID'

Which looks like:

ubuntu-geoip-pr@2382
chrome@2453
chrome@2453
chrome@2453
chrome@2453
chrome@2453
chrome@2453
chrome@2453
chrome@2453
rhythmbox@4759
rhythmbox@4759
rhythmbox@4759

Finally, I want to get the output as:

1
8
3

This corresponds to the number of occurrences of each of the items in the previous output.

Problem in full:

The sockstat command outputs the info for some networking stats for the localhost. I first print out a single key from the second and third columns from the output (PROCESS and PID, respectively), in the form PROCESS@PID. Then, I want to calculate the frequency of each unique key from that output. One way to do this is to use the awk getline structure, but that seems works for files, and I have not been able to make it pull input directly from the above command.

I do not want to use temporary files, as that takes away the elegance of the solution.

Upvotes: 0

Views: 2051

Answers (3)

Steve
Steve

Reputation: 54392

You could simplify your command:

sockstat | awk 'NR>1 { a[$2 "@" $3]++ } END { for (i in a) print a[i], i }'

If you just want the counts, simply edit the print statement:

sockstat | awk 'NR>1 { a[$2 "@" $3]++ } END { for (i in a) print a[i] }'

Upvotes: 0

Abhishek
Abhishek

Reputation: 325

sockstat | awk '{print $2 "@" $3}' | grep -v '^PROCESS@PID' | sort | uniq -c | awk '{print $1}'

Upvotes: 1

ddoxey
ddoxey

Reputation: 2063

How about this?

sockstat | grep -v PROCESS | awk '{key=$2"@"$3; count[key]++} END {for ( key in count ) { print key" "count[key]; } }'

Upvotes: 0

Related Questions