当错误代码之前的行数不一致时,如何对错误代码之前出现的字符串进行grep

当错误代码之前的行数不一致时,如何对错误代码之前出现的字符串进行grep,grep,Grep,当我在日志文件中发现错误字符串时,我需要知道是什么原因导致的 错误。但失败的文件名是随机数行 在错误字符串之前。例如: 日志文件: This **specific backup.tar** failed\n Because of this\n Or because of this\n Then some random lines of output\n Exiting -- searched-for string appears\n 如果我使用'grep Exiting--before

当我在日志文件中发现错误字符串时,我需要知道是什么原因导致的 错误。但失败的文件名是随机数行 在错误字符串之前。例如:

日志文件:

This **specific backup.tar** failed\n 
Because of this\n
Or because of this\n
Then some random lines of output\n  
Exiting -- searched-for string appears\n 
如果我使用'grep Exiting--before context=4',我会发现backup.tar失败。但随机线的数量各不相同

所以我想使用--before context=“string”,或者在本例中--before context=“.tar”


你知道怎么做吗

不幸的是,
grep
无法胜任这项工作。在
awk
中尝试以下操作:

$ cat foo.txt
This specific backup.tar failed
Because of this
Or because of this
Then some random lines of output
Exiting -- searched-for string appears
$ awk '/This specific .* failed/ { filename = $3 } /searched-for string/ { print filename }' foo.txt
backup.tar

您是否考虑过使用grep而不是
grep
。我知道可能存在错误的文件名。如果它确实存在于该日志文件中,则向后查找失败的备份。可能:grep“Exiting”日志文件,如果存在,则在日志文件中搜索“/failed/”。谢谢你的建议!