简体   繁体   中英

Count number of occurrences in file. conditional pattern matching

Sorry if the title doesn't make it clear.

I have a file to be read every 15 mins and find a particular pattern in it (eg timeout). File does not have any fixed update frequency.

Outcome expected:- 1. if pattern is found 3 times in 15 mins, run command1. 2. if pattern is found 5 times in 15 mins, run command2.

File to be read from last read position for each check.

Thanks, GRV

One way to do this is with a cron job. It is more complicated than other solutions but it is very reliable (even if your "check script" crashes, it will be called up again by cron after the period elapses). The cron could be:

*/15 * * * * env DISPLAY=:0 /folder/checkscript >/dev/null 2>&1

The env DISPLAY=:0 might not be needed in your case, or it might be needed, depending on your script (note: you might need to adapt this to your case, run echo $DISPLAY to find out your variable on the case).

Your "checkscript" could be:

#!/bin/bash
if [ -f /tmp/checkVarCount ]; then oldCheckVar="$(cat /tmp/checkVarCount)"; else oldCheckVar="0"; fi
checkVar="$(grep -o "pattern" /folder/file | wc -l)"
echo "$checkVar" > /tmp/checkVarCount
checkVar="$(($checkVar-$oldCheckVar))"
if [ "$checkVar" -eq 3 ]; then command1; fi
if [ "$checkVar" -eq 5 ]; then command2; fi
exit

It is not included on your question, but if you meant to run the commands as well if the pattern is found 4 times or 7 times, then you could change the relevant parts above to:

if [ "$checkVar" -ge 3 ] && [ "$checkVar" -lt 5 ]; then command1; fi
if [ "$checkVar" -ge 5 ]; then command2; fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM