grep的时间戳和文字 [英] grep for timestamp and word
问题描述
所以,我想通过一个日志文件计数包含一个时间戳,是最后30分钟,一个字内的线给grep。
我有工作code寻找时间戳:
的grep^ $(日期-d -30minute +'%Y-%M-%D%H')/路径/要/的/ DERP |厕所-l
这是例如日志文件可能是:
2014年8月7日00:00:03.001 000 GoogleGeo $ C $内部CService等等等等等等
2014年8月7日00:00:01.001 000载体检查java.net.SocketTimeoutException
如果这两个项目最后半小时内ocured,我怎么算第二行,但不是第一?我曾尝试只需添加另一个管道,但我从来没有得到正确的结果:
的grep^ $(日期-d -30minute +'%Y-%M-%D%H')/路径/要/的/ DERP |厕所-l | grep按例外
与code的主要问题是,你的grep
ING的日期戳即是整整30分钟前而不是在最后30分钟的任何时间。
您可以完成你想要什么awk中通过将当前shell的日期秒作为一个变量。然后,你可以在日志中的时间戳转换成日期秒,减去从当前日期变量,看它是否是在最后30分钟(1800秒)。
的awk -v电流= $(日期+%S)-v IGNORECASE = 1 -F \\。 '开始 {
N = 0
}
/ ^ [0-9] {1,4} - [0-9] {1,2} - [0-9] {1,2} [0-9] {2}:[0-9] {2 }:[0-9] {2} ./&放大器;&安培; /异常/ {
时间= $ 1
格式=\\\\ \\\\ 1 \\\\ 2 3 4 \\\\ \\\\ \\\\ 5 6
秒= mktime(gensub(/(....) - (..) - (..)(..):(..):(..)/,格式,,时间))
如果((电流 - 秒)< = 1800)
ñ++
}结束{
打印传单N
}'/路径/要/的/ DERP
So I am trying to grep through a log file counting lines that contain a time stamp that is within the last 30 minutes and a word. I have working code for finding the time stamp:
grep "^$(date -d -30minute +'%Y-%m-%d %H')" /path/to/the/derp | wc -l
An example log file could be:
2014-08-07 00:00:03.001 000 GoogleGeoCodeService blah blah blah
2014-08-07 00:00:01.001 000 carrier check java.net.SocketTimeoutException
If both entries ocured within last half hour, how do I count the second line but not the first? I have tried just adding another pipe but I never get the correct result:
grep "^$(date -d -30minute +'%Y-%m-%d %H')" /path/to/the/derp | wc -l | grep -i "exception"
The main problem with your code is that you're grep
ing for date stamps that are exactly 30 minutes ago instead of any time in the last 30 minutes.
You could accomplish what you want with Awk by passing the current shell's date in seconds as a variable. Then you can convert the datestamp in the log to date in seconds and subtract that from the current date variable to see if it's in the last 30 minutes (1800 seconds).
awk -v current=$(date +%s) -v IGNORECASE=1 -F\. 'BEGIN {
n=0
}
/^[0-9]{1,4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{2}:[0-9]{2}:[0-9]{2}./ && /exception/ {
time=$1
format="\\1 \\2 \\3 \\4 \\5 \\6"
seconds=mktime(gensub(/(....)-(..)-(..) (..):(..):(..)/, format, "", time))
if((current - seconds) <= 1800)
n++
}END{
print n
}' /path/to/the/derp
这篇关于grep的时间戳和文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!