Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using awk to count the number of occurrences of a word in a column

Tags:

linux

bash

awk

03/03/2014 12:31:21 BLOCK 10.1.34.1 11:22:33:44:55:66

03/03/2014 12:31:22 ALLOW 10.1.34.2 AA:BB:CC:DD:EE:FF

03/03/2014 12:31:25 BLOCK 10.1.34.1 55:66:77:88:99:AA

I am trying to use awk to count the number of occurrences of the word "block" and "access" above in one command.

I tried the word "block" at first but my counter does not appear to be working. Can anyone see where my code is wrong?

awk ' BEGIN {count=0;}  { if ($3 == "BLOCK") count+=1} end {print $count}' firewall.log
like image 444
user3578872 Avatar asked Sep 05 '25 16:09

user3578872


1 Answers

Use an array

awk '{count[$3]++} END {for (word in count) print word, count[word]}' file

If you want "block" specifically: END {print count["BLOCK"]}

like image 182
glenn jackman Avatar answered Sep 07 '25 06:09

glenn jackman