Grep a word and find its Count from log file for different times Grep a word and find its Count from log file for different times unix unix

Grep a word and find its Count from log file for different times


import repattern=re.compile(r"\d{4}-\d{1,2}-\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2}:|Error",re.IGNORECASE)ll=pattern.findall(x)d={}for x in ll:    if x!="Error":        d[x]=0        last=x    else:        d[last]=d[last]+1print d

Here x is your data or file.read().


Simple job with Awk.

awk '/^[0-9][0-9][0-9][0-9]-[01][0-9]-[0-3][0-9] [012][0-9]:[0-5][0-9]:[0-6][0-9]:/ {       t=$0 }    /Error/ { ++e[t] }    END { for (s in e) print s "Error-Count=" e[s] }' logfile


A direct awk:

awk '/^201[0-9].*:/{if (cont){print cont}cont=0;printf $0}/Error/{cont+=1}END{print cont}' infile

Explained code:

awk '/^201[0-9].*:/{ # Timestamp pattern reached                    if (cont){                              print cont # print previus timestamp                             }           # counter if exists and not zero                    cont=0 # initialize actual timestamp counter                     printf $0                   } #  print timestamp WITHOUT linebreak            /Error/{ # Error patter reached                    cont+=1 # Aaccumulated count                   }     END{        print cont # print remainder counter        }' infile