4

I have logs like as given sample below, where I'm simply looking for a SUCCESS string in the log file and counting the total.

$ cat ansible.log
lnx-host01.tin.com | SUCCESS => {"changed": false, "ping": "pong"}
lnx-host02.tin.com | SUCCESS => {"changed": false, "ping": "pong"}

This is what the simple straightforward way, but I'm wondering if it can be done with awk itself as a one liner without passing to the wc command.

$ awk '/SUCCESS/{print $0}'  ansible.log | wc -l
66

OR

$ awk '/SUCCESS/' ansible.log| wc -l
66
0

1 Answer 1

5

Here it is:

awk 'BEGIN { count=0 } /SUCCESS/ { count++ } END { print count }' ansible.log

Of course this would have also worked:

grep -c SUCCESS ansible.log
7
  • +1 for short grep solution (was going to post it but you were faster) Dec 8, 2018 at 14:44
  • @ A.B , thnx , how about awk '/SUCCESS/ {count++} END{print count}' ansible.log
    – krock1516
    Dec 8, 2018 at 14:58
  • 1
    Works almost fine too. It will print an empty line instead of 0 in case of no match (then count is considered by default an empty string). So if you can garantee there's always at least one SUCCESS then it's good enough. We're not on Code Golf heh.
    – A.B
    Dec 8, 2018 at 15:06
  • That's fine @A.B :-) , indeed we are not in Code Golf .
    – krock1516
    Dec 8, 2018 at 15:14
  • 1
    @krock1516 change print count to print count+0 and you will be fine.
    – user313992
    Dec 8, 2018 at 20:07

Not the answer you're looking for? Browse other questions tagged .