![读取 2 个日期之间包含“ERROR”一词的日志](https://linux22.com/image/135882/%E8%AF%BB%E5%8F%96%202%20%E4%B8%AA%E6%97%A5%E6%9C%9F%E4%B9%8B%E9%97%B4%E5%8C%85%E5%90%AB%E2%80%9CERROR%E2%80%9D%E4%B8%80%E8%AF%8D%E7%9A%84%E6%97%A5%E5%BF%97.png)
日志的格式为:
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
,awk
或sed
实现都可以
编辑: $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