在文件中查找多个字符串,并通过电子邮件发送任何已定义字符串的出现
我想编写一个 shell 脚本,它将从给定的日志文件(例如 /var/log/messages)中查找多个字符串的出现,例如“Errors|Notice|Warnings”。如果任何字符串匹配,它应该向指定的邮件 ID 发送邮件通知。
我可以使用:
grep -i -E '^Errors|Notice|Warnings' /var/log/messages
但我的主要问题是,日志文件总是在增长,如果我想在cron中添加这个脚本,我如何记录我在上次执行脚本时已经检查过的文件行或内容?
例如,如果日志文件有 100 行,并且我已经使用 cat 或类似的东西读取了该文件,那么在第二次执行之前,该文件变为 300 行,那么现在我想从 101 行号读取到 300 行。
任何人都可以建议吗我怎样才能记录这个?
I want to write a shell script which will find the occurence of multiple strings like "Errors|Notice|Warnings" from a given log file, such as /var/log/messages. If any string matches it should send a mail notification to specified mail ID.
I can use:
grep -i -E '^Errors|Notice|Warnings' /var/log/messages
But my main problem is, the log file always growing, and if I want to add this script in cron, how can I record the file line or contents that I had already checked on the last execution of my script?
For example, if the log file is 100 lines and I have read the file using cat or anything similar, then before second execution, the file becomes 300 lines, then now i want to read from 101 line number to 300.
Can anyone please suggest how I can record this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用以下脚本来执行此操作:
顺便说一句,您的 regx 中有问题,它应该是
'Errors|Notice|Warnings'
而不是'^Errors|Notice|Warnings'
You can use following script to do that:
btw you have a problem in your regx, it should be
'Errors|Notice|Warnings'
instead of'^Errors|Notice|Warnings'
轮换日志文件可能是最好的解决方案。
但是如果你想从
line_first
到line_last
进行 grep 文件,你可以使用sed
:例如,从输入流中获取从 100 到 110 的行:
Rotating your log file could be the best solution.
But if you want to grep file from
line_first
toline_last
you can usesed
:For example, get line from 100 to 110 from input stream: