How do I run grep command for a range of inputs?

2019-08-23 07:11发布

I need the following grep command to find how many requests per hour are received in logs:

grep 'login log' filelog.txt | grep -c '2017-08-30 ":00 to :23"'

Here the hour 00 till 23, I need to pass as a parameter. For instance, for date 30 I need to see each hour what was the count.

Is it possible using a single command? Currently I have to execute one command for each hour manually. For example,

$grep 'login log' filelog.txt | grep -c '2017-08-30 :00'
123
$grep 'login log' filelog.txt | grep -c '2017-08-30 :01'
456

Here are log lines inside the file which I wanted to count hourly based on time (second column):

2017-08-30 20:19:47 INFO  com.java.JavaFile:123 - login log  abcduser

2条回答
霸刀☆藐视天下
2楼-- · 2019-08-23 07:25

So, going by what you say rather than what you do:

Your input (augmented for testing):

cat filelog.txt
2017-08-30 20:19:47 INFO  com.java.JavaFile:123 - user login  abcduser
2017-08-30 20:29:47 INFO  com.java.JavaFile:123 - user login  abcduser
2017-08-30 21:17:47 INFO  com.java.JavaFile:123 - user login  abcduser
2017-08-30 21:19:47 INFO  com.java.JavaFile:123 - user login  abcduser

Desired result? Printing the hour and the count of matches:

awk '/login/ {a[gensub(/(..):.*/,"\\1",1,$2)]++;b[gensub(/(..):.*/,"\\1",1,$2)]=gensub(/(..):.*/,"\\1",1,$2)} END{n=asorti(a,s); for(i=1;i<=n;i++){print b[s[i]]"\t"a[s[i]]}}' filelog.txt
20  2
21  2
查看更多
▲ chillily
3楼-- · 2019-08-23 07:35
grep "yourstring" filelog.txt |
   grep -Eo "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}" | sort | uniq -c
查看更多
登录 后发表回答