如何在Shell脚本中每60分钟在目录的日志文件中查找grep值?

问题描述 投票:0回答:1

我有一个名为/ qfs / input / ad_logs的目录。每隔15分钟左右,会将一个新文件转储到此目录中。我需要每小时检查一次此目录,以查看日志的第10个字段中是否有某个值。已经使用命令lzop -cd file_name_20200209.lzo | cut -f10 -d, | grep mcid=在日志中查找值。

我该如何执行此Shell脚本来自动执行该过程,并在日志中提醒我发现的值?

linux bash shell scripting bin
1个回答
2
投票

创建脚本:

#!/bin/sh
if lzop -cd file_name_20200209.lzo | cut -f10 -d, | grep -q mcid=; then
      # alert me of the found value in the logs?
      logger -p local3.info -t "VERY_IMPORTANT_SCRIPT" "alert! The value was found in the logs"
fi

[然后将此脚本添加到cron(如果有),或者将其添加到system timer service,如果系统使用的systemd将每隔一小时运行一次脚本)。例如,创建两个文件:

# /etc/systemd/service/very_important_script.timer
[Unit]
Description=Run very_important_script hourly

[Timer]
OnCalendar=hourly
Persistent=true

[Install]
WantedBy=timers.target

[Unit]
Description=very_important_script 

[Service]
ExecStart=/path/to/the/very_important_script

[Install]
WantedBy=multi-user.target

并执行systemctl deamon-refresh ; systemctl enable very_important_script.timer ; systemctl start very_important_script.timer启动计时器。

例如,您可以只考虑最近一小时更改的文件:

#!/bin/sh
if 
      find . -maxdepth 1 -type f -name 'file_name_*.lzo' -mmin -60 |
      xargs lzip -cd | 
      cut -f10 -d, | grep -q mcid=  
      # maybe add -m1 to grep?
then
      # alert me of the found value in the logs?
      logger -p local3.info -t "VERY_IMPORTANT_SCRIPT" "alert! The value was found in the logs"
fi
© www.soinside.com 2019 - 2024. All rights reserved.