我正在尝试在过去一个小时内查看日志中的某些消息。日志以这种方式格式化:
[1/18/19 9:59:13:791 CST] <Extra text here...>
我在与awk进行日期比较时遇到了麻烦,所以我的想法是转换为时代并进行比较。我正在使用字段1,并从字段2中删除了毫秒,然后删除了[]
(尽管我想我可以[
来做)。
while read -r line || [[ -n "$line" ]]
do
log_date_str="$(awk '{gsub("\\[|\\]", "");print $1" "substr($2,1,length($2)-4)}' <<< "$line")"
log_date="$(date -d "$log_date_str" +%s)"
[[ $(($(date +%s)-$log_date)) -le 3600 ]] && echo "$line"
done < /path/to/file
当我尝试对日志文件运行此操作时,出现此错误:
date: invalid date `************ S'
-bash: 1547832909-: syntax error: operand expected (error token is "-")
以单个日期为例,例如“ 1/18/19 9:59:13”可用于将日期转换为纪元,但我不确定该出错的地方。
答案 0 :(得分:0)
As the comments pointed out, I was getting data that was not a date since it was parsing the entire log. Grepping the input file for my desired text solved my problems, and I've changed to Charles' suggestion.
while read -r line || [[ -n "$line" ]]
do
log_date_str="$(awk '{gsub("\\[|\\]", "");print $1" "substr($2,1,length($2)-4)}' <<< "$line")"
log_date="$(date -d "$log_date_str" +%s)"
(( ( $(date +%s) - log_date ) <= 3600 )) && echo "$line"
done < <(grep ERROR_STRING /path/to/file.log)