解析某些时间戳之间的文件内容 [英] Parse contents of a file between certain timestamps
问题描述
我有一个包含了大量的信息的日志文件,我想只解析该文件落入过去24小时内的内容
I have a log file that contains a lot of information and I would like to only parse the contents of that file which fall within the last 24 hours
文件中的每一行与时间戳开头,如 1月31日13时13分02秒
,然后有一个日志信息。
Each line in the file begins with a timestamp such as Jan 31 13:13:02
and then has a log message.
我目前有发现开始和结束时间这样的批处理文件
I currently have a batch file that finds the start and end time like this
start=$(date +"%b %d %H:%M:%S" --date="-1 day")
end=$(date +"%b %d %H:%M:%S")
我当时希望利用这些时间用的grep -cdata_to_find
一起查找某一日志消息出现的次数,这样我可以然后采取行动关于这个版本。
I was then hoping to use these times along with a grep -c "data_to_find"
to find the number of occurrences of a certain log message so that I can then act on this later.
总之,我怎样才能兼顾次,然后用grep一个字符串的出现次数的内容中说文件?
In short, How can I take into account the times and then grep the content for the number of occurrences of a string within said file?
我在Linux系统上,并有与使用SED,AWK,任何解决方案没有问题,GREP等。
I am on a linux system and have no issue with any solution that uses SED, AWK, GREP etc.
推荐答案
无需编写shell脚本(特别是如果它不排序)没那么简单。
Not so simple without writing a shell script (especially if it's not sorted).
我会尝试这样的事情来获得在1天前,现在的grep -c
管不管你想输出的所有行(插值如果需要),然后。下面的说明假定日期格式是一样的东西 1月31日13时13分02秒
(月和日之间的2个空格)
I would try something like this to get all the lines between 1 day ago and now (interpolate as needed), and then grep -c
pipe whatever you want from output. Note below assumes date format is something like Jan 31 13:13:02
(2 spaces between Month and Day)
#!/bin/bash
yest=$(date -d "1 days ago" '+%s')
today=$(date '+%s')
while read -r line; do
date=
[[ $line =~ ^[[:alpha:]]+[[:blank:]][[:blank:]][0-9]+[[:blank:]][0-9]+':'[0-9]+':'[0-9]+ ]] && date="${BASH_REMATCH[0]}"
[[ -n $date ]] && date=$(date -d "$date" '+%s')
[[ -n $date && $date -ge $yest && $date -le $today ]] && echo "$line"
done < logfile
这篇关于解析某些时间戳之间的文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!