I want to write a bash script that will find number of occurrence of a string from last ten minutes logs. i used a while loop but it is too slow to run as it is increasing each second. i want a simple sed or grep command that should be replaced by loop and should work efficiently.
#!/bin/bash
log_file="logfile.log"
search_string="your_search_string"
COUNTER=0
current_time=$(date +%s)
start_time=$((current_time-600))
while [ $start_time -le $current_time ]
do
date_time=$(date -d @$start_time +"%Y-%m-%d %H:%M:%S")
count=$(grep "$date_time" "$log_file" | grep "$search_string" | wc -l)
if [ $count -eq 1 ]; then
COUNTER=$[$COUNTER +1]
return
fi
echo "$date_time: $COUNTER occurrences"
start_time=$((start_time+1))
done
echo "$COUNTER occurrences"
My log file timestamp looks like:
INFO \[RMI TCP Connection(4)-10.103.5.24\] 2022-11-29 15:21:01,552 Server.java:225 - Stop listening
WARN \[RMI TCP Connection(6)-10.103.5.24\] 2022-11-29 15:21:07,948 StorageService.java:359 - Stopping gossip
INFO \[RMI TCP Connection(6)-10.103.5.24\] 2022-11-29 15:21:07,949 Gossiper.java:1456 - Announcing shutdown
I want to change the do while loop with some sed
or grep
command