我想在我的日志文件中获得一小时的间隔。这是一个示例日志:
2016-03-30|00:54:46,060|[WARNING]
2016-03-30|00:55:46,318|[OK]
2016-03-30|00:55:46,318|[OK]
2016-03-30|01:42:13,691|[UNKNOWN]
2016-03-30|01:53:16,356|[CRITICAL]
2016-03-30|02:56:41,410|[WARNING]
2016-03-30|02:42:13,691|[UNKNOWN]
2016-03-30|02:53:16,356|[UNKNOWN]
2016-03-30|03:56:41,410|[WARNING]
我定义了一些变量:date_now=date +"%Y-%m-%d %H:%M:%S,%3N"
,date_minus_one=date -d "-1 hour" +"%Y-%m-%d %H:%M:%S,%3N"
和date_minus_two=date -d "-2 hour" +"%Y-%m-%d %H:%M:%S,%3N"
。我知道你可以通过制作`date_now> = date_minus_one和date_now< = date_minus_two来获得每小时的逻辑。但是我不知道如何用awk,sed或grep来表达它。
我希望输出结果为:
2016-03-30|02:56:41,410|[WARNING]
2016-03-30|02:42:13,691|[UNKNOWN]
2016-03-30|02:53:16,356|[UNKNOWN]
等等,以获得1小时的日志间隔。
答案 0 :(得分:1)
使用grep
:
grep -E '^2016-03-30\|02:[0-9]{2}:[0-9]{2},' file.log
来自变量:
hour_to_search=$(date '+%F\|%H')
grep -E "^${hour_to_search}:[0-9]{2}:[0-9]{2}," file.log
或使用特定日期时间作为参考:
hour_to_search=$(date -d '30 Mar 2016 02 AM' '+%F\|%H')
grep -E "^${hour_to_search}:[0-9]{2}:[0-9]{2}," file.log
示例:强>
$ cat file.log
2016-03-30|00:54:46,060|[WARNING]
2016-03-30|00:55:46,318|[OK]
2016-03-30|00:55:46,318|[OK]
2016-03-30|01:42:13,691|[UNKNOWN]
2016-03-30|01:53:16,356|[CRITICAL]
2016-03-30|02:56:41,410|[WARNING]
2016-03-30|02:42:13,691|[UNKNOWN]
2016-03-30|02:53:16,356|[UNKNOWN]
2016-03-30|03:56:41,410|[WARNING]
$ hour_to_search=$(date -d '30 Mar 2016 02 AM' '+%F\|%H')
$ echo "$hour_to_search"
2016-03-30\|02
$ grep -E "^${hour_to_search}:[0-9]{2}:[0-9]{2}," file.txt
2016-03-30|02:56:41,410|[WARNING]
2016-03-30|02:42:13,691|[UNKNOWN]
2016-03-30|02:53:16,356|[UNKNOWN]
答案 1 :(得分:0)
制作仅包含日期和小时("%Y-%m-%d|%H:"
)的搜索模式,并使用它来过滤您提到的任何一种工具
答案 2 :(得分:0)
您也可以尝试类似
的内容csplit -zk sample.log '/2016-03-30|0'{0..9}/ '{*}'
答案 3 :(得分:0)
#To get the current date and hour
hour=$( date +'%F|%H')
#Filter the logs
grep $hour log
注:编辑根据评论中的建议。
答案 4 :(得分:0)
试试这个
awk -F "|" '{ print "date -d\""$1 " " $2"\" +%s.%N" "'\''|" $0 "'\''" }' mylog.file |\
bash |\
awk -F "|" -v OFS="|" \
-v startdate=$(date -d "2016-03-30 01:42:13,691" "+%s.%N") \
-v enddate=$(date -d "2016-03-30 02:53:16,356" "+%s.%N") \
'$1>=startdate && $1<=enddate {$1="";print}'
根据您的需要调整startdate
和enddate
,自EPCOH和纳秒后应为秒:格式为"+%s.%N"
awk ...
的第一部分只是构建一个date
命令行并使用bash
来执行它。目标是在每行的开头添加自EPOCH和纳秒之后的秒数。
最终awk
比较日期,以秒为单位。纳秒格式并仅打印范围内的行:[startdate .. enddate]
测试:
$ awk -F "|" \
'{ print "date -d\""$1 " " $2"\" +%s.%N" "'\''|" $0 "'\''" }' mylog.file |\
bash |\
awk -F "|" -v OFS="|" \
-v startdate=$(date -d "2016-03-30 01:42:13,691" "+%s.%N") \
-v enddate=$(date -d "2016-03-30 02:53:16,356" "+%s.%N") \
'$1>=startdate && $1<=enddate {$1="";print}'
|2016-03-30|01:42:13,691|[UNKNOWN]
|2016-03-30|01:53:16,356|[CRITICAL]
|2016-03-30|02:42:13,691|[UNKNOWN]
|2016-03-30|02:53:16,356|[UNKNOWN]