如何根据错误关键字从日志文件中提取行?

How to extract lines from log files based on an error keyword?

这是一个示例日志文件(如下)。当关键字 ORA-02063 存在于日志中的任何行时,我想提取日志文件中具有相同时间戳的所有行。

我曾尝试使用 grep,但没有成功,因为我无法提取时间戳。

20200814 13:54:34 DEBUG (com.test.test.test.test2Servlet) [doPost]  Incoming XML request: <?xml version="1.0" encoding="UTF-8"?>
<webdoc>
</contract>
<notes>


some data

</notes>
    </contract>
</webdoc> 
20200814 13:54:34 ERROR (com.test.test.test.test2Servlet) [doPost] request failed: ccom.test.test.test.test2Servlet.exception.SystemFailureException: Database operation failed  - caused by: java.sql.BatchUpdateException: ORA-01461: can bind a LONG value only for insert into a LONG column
ORA-02063: preceding stringstring from string```



你可以试试这个,不是最好的,而是一个解决方案

grep "`grep 'ORA-02063' logfile -B1 | cut -d ' ' -f1,2 | head -n 1`" logfile

尝试使用文件 webdoc 中的示例数据:

dayte=$(awk -v str="ORA-01461" '{ if (match([=10=],str)) { print substr([=10=],0,17) } }' webdoc)

使用 awk,传递要搜索的字符串,如果它存在于行中,则使用 substr 函数获取日期和时间戳并打印。将结果读入变量 dayte。

在设置了变量 dayte 的情况下,使用 sed 打印所需的行:

sed -n '/'"$dayte"'/,/^<\/webdoc>/p' webdoc

将包含相关日期的所有行打印到结束的 webdoc 标记。

注意 - 确保在 sed 命令中引用了 dayte 变量。