在文件中查找多个字符串,并通过电子邮件发送任何已定义字符串的出现

发布于 2024-12-29 17:19:09 字数 418 浏览 4 评论 0原文

我想编写一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

生生不灭 2025-01-05 17:19:09

您可以使用以下脚本来执行此操作:

start=0

[[ -f last-processed ]] && start=$(<last-processed)

start=$((start+1))

tail +$start /var/log/messages | grep -i -E 'Errors|Notice|Warnings' &&\
wc -l /var/log/messages | awk '{print $1}' > last-processed

顺便说一句,您的 regx 中有问题,它应该是 'Errors|Notice|Warnings' 而不是 '^Errors|Notice|Warnings'

You can use following script to do that:

start=0

[[ -f last-processed ]] && start=$(<last-processed)

start=$((start+1))

tail +$start /var/log/messages | grep -i -E 'Errors|Notice|Warnings' &&\
wc -l /var/log/messages | awk '{print $1}' > last-processed

btw you have a problem in your regx, it should be 'Errors|Notice|Warnings' instead of '^Errors|Notice|Warnings'

扛刀软妹 2025-01-05 17:19:09

轮换日志文件可能是最好的解决方案。

但是如果你想从 line_firstline_last 进行 grep 文件,你可以使用 sed

例如,从输入流中获取从 100 到 110 的行:

gt; line_first=100; line_last=110
gt; seq 1 1000 | sed -n "${line_first},${line_last}p"
100
101
102
103
104
105
106
107
108
109
110

Rotating your log file could be the best solution.

But if you want to grep file from line_first to line_last you can use sed:

For example, get line from 100 to 110 from input stream:

gt; line_first=100; line_last=110
gt; seq 1 1000 | sed -n "${line_first},${line_last}p"
100
101
102
103
104
105
106
107
108
109
110
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文