Count the number of occurences in a file in the last 7 days

Viewed 57

Input:

cat log.txt

2021-01-15 00:00:14: Installing hotfix ...
2021-01-15 00:02:07: Hotfix successfully installed!
2021-01-15 00:02:07: Finished
2021-02-07 00:00:14: Installing hotfix ...
2021-02-07 00:02:07: Hotfix successfully installed!
2021-02-07 00:02:07: Finished
2021-02-08 12:00:14: Started - Looking for available hotfixes ...
2021-02-08 12:00:14: Updating the hotfix list
2021-02-08 12:00:14: Finished

I would like to create a daily cronjob that updates a file.txt with the number of occurrences for the word installed, but only for the last 7 days. So, whenever I read file.txt it should contain the number of hotfixes installed in the last 7 days.

current date: 2021-02-08

Output:

cat file.txt
1

I know I can use grep -c "installed" log.txt in order to count all the occurrences in the log file. But how can I modify it so that grep only counts the occurrences from the last 7 days? The dates will always change, as new lines are added daily, so I cannot provide fixed dates in the grep script. Also, there might be multiple installed occurrences in a given day, so I cannot grep by line number.

2 Answers
awk -v d="$(date -d "7 days ago" "+%F")" '$1 > d && /installed/{c++}END{print c}' log.txt >file.txt

Using the date from GNU coreutils and plain bash:

#!/bin/bash

linecount=0
weekago=$(date -d "-7 days" +%F)
while read -r line; do
        [[ $line > $weekago ]] && [[ $line = *installed* ]] && ((++linecount))
done < log.txt
echo $linecount > file.txt
Related