How to Use Hash Map to Count the Frequencies of Values and Iterate the Key-Value Pairs in AWK?

in blurt •  4 years ago 

AWK is a powerful text-processing programming language. Given a multi-million lines of text file containing the following data - we want to know the frequencies the delegation at each integer interval e.g. 2, 3, 4:

First, we output the text file to console using cat then pipe it into grep to filter out non-data rows, and then we can execute the awk script.

cat steem3.txt | grep "delegates" | awk '$6 > 0 {
   data[int($6)]++
} 

END { 
  for (sp in data) {
     print (sp, "=", data[sp]);
  } 
}' 

It filters out the records that have zero values (undelegation records) - then we round the fraction numbers into integers and count them in a hash map.

Basically, we don't have to declare the hash table prior to using it. And we can access it using the syntax map[key]. And at the END section, we can iterate the keys in the hash map in awk and print each value:

for (key in map) {
   print ("key is ", key, ", value is ", map[key]);
}

--EOF (The Ultimate Computing & Technology Blog) --

Reposted to Blog

Every little helps! I hope this helps!

Steem/Blurt On!~

If you like my work, please consider voting for me or Buy Me a Coffee, thanks!
https://steemit.com/~witnesses type in justyy and click VOTE



Alternatively, you could proxy to me if you are too lazy to vote!

Also: you can vote me at the tool I made: https://steemyy.com/witness-voting/?witness=justyy

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!