读取 2 个日期之间包含“ERROR”一词的日志

读取 2 个日期之间包含“ERROR”一词的日志

日志的格式为:

2018-06-25 00:00:20,073 DEBUG SAMPLE TEXT CONTENT
2018-06-26 00:00:20,073 ERROR SAMPLE TEXT CONTENT
2018-06-26 17:37:20,073 ERROR SAMPLE TEXT CONTENT
2018-06-26 19:00:20,073 DEBUG SAMPLE TEXT CONTENT
2018-06-27 00:00:20,073 DEBUG SAMPLE TEXT CONTENT
2018-06-28 00:00:20,073 ERROR SAMPLE TEXT CONTENT
2018-06-29 00:00:20,073 ERROR SAMPLE TEXT CONTENT
2018-06-30 00:00:20,073 DEBUG SAMPLE TEXT CONTENT
2018-07-01 11:00:20,073 ERROR SAMPLE TEXT CONTENT
2018-07-02 02:00:20,073 DEBUG SAMPLE TEXT CONTENT
2018-07-02 00:00:20,073 ERROR SAMPLE TEXT CONTENT
2018-07-03 20:00:20,073 ERROR SAMPLE TEXT CONTENT

我想查找并显示 2 个日期(假设 2018-06-26 到 2018-07-02)之间包含“ERROR”一词的所有日志。我将动态获取日期,因此它们将是变量 $FROM 和 $TO。

任何grep,awksed实现都可以

编辑: $TO 和 $FROM 日期都应该包含在内,并且可能需要访问多个日志文件,因此日志可能无法排序

答案1

awk,使用-v选项将 shell 变量传递给 awk 变量:

$ awk -v from="$FROM" -v to="$TO" 'from <= $1 && $1 <= to && /ERROR/' log.txt
2018-06-26 00:00:20,073 ERROR SAMPLE TEXT CONTENT
2018-06-26 17:37:20,073 ERROR SAMPLE TEXT CONTENT
2018-06-28 00:00:20,073 ERROR SAMPLE TEXT CONTENT
2018-06-29 00:00:20,073 ERROR SAMPLE TEXT CONTENT
2018-07-01 11:00:20,073 ERROR SAMPLE TEXT CONTENT
2018-07-02 00:00:20,073 ERROR SAMPLE TEXT CONTENT

答案2

使用 AWK:

awk '/'$FROM'/,/'$TO'/ {print $0}' log.txt | grep ERROR

使用 sed:

sed -n '/'$FROM'/,/'$TO'/p' log.txt | grep ERROR

答案3

简单而有效;

egrep '2018-06-26|2018-07-02' log file | grep "ERROR"

答案4

循环日期 (通过):

FROM=2018-06-26
TO=2018-07-02
d=$FROM
while [ $d != $TO ]; do 
  grep "^${d}.*ERROR" logfile
  d=$(date -I -d "$d + 1 day")
done

相关内容