Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash check if string appears more than X times in logs

I have a log file like:

135.148.41.73 - [11/Dec/2022:12:21:11 +0100]  - "-" code=400 upstream="-" req=0.449 up=- ua="-"
135.148.41.73 - [11/Dec/2022:12:21:14 +0100]  - "-" code=400 upstream="-" req=0.413 up=- ua="-"
135.148.41.73 - [11/Dec/2022:12:21:15 +0100]  - "-" code=400 upstream="-" req=1.001 up=- ua="-"
135.148.41.73 - [11/Dec/2022:12:21:16 +0100]  - "-" code=400 upstream="-" req=1.002 up=- ua="-"
45.87.212.41 - [11/Dec/2022:12:22:50 +0100]  - "-" code=400 upstream="-" req=0.004 up=- ua="-"

I need to perform some action if IP appears more than X times on the logs.

Using awk '{print $1}' access.log | sort | uniq -c | sort -rn I can count them, but how do I perform action on it using bash?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Like:

  1. For each IP that appears more than 5 times in access.log, do something.

Thanks.

>Solution :

#!/usr/bin/env bash

while IFS= read -r ip; do
    some_command "$ip"
done < <(awk '++cnt[$1] == 5{print $1}' file)

Replace some_command with whatever it is you want to do with that IP.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading