Bash: How to count and sort requests by IP from the access logs

Posted . Visible to the public.

Example

87.140.79.42 - - [23/Jan/2024:09:00:46 +0100] "GET /monitoring/pings/ HTTP/1.1" 200 814 "-" "Ruby"
87.140.79.42 - - [23/Jan/2024:09:00:46 +0100] "GET /monitoring/pings/ HTTP/1.1" 200 814 "-" "Ruby"
87.140.79.41 - - [23/Jan/2024:09:00:46 +0100] "GET /monitoring/pings/ HTTP/1.1" 200 814 "-" "Ruby"
87.140.79.42 - - [23/Jan/2024:09:00:46 +0100] "GET /monitoring/pings/ HTTP/1.1" 200 814 "-" "Ruby"

Goal

Count and sort the number of requests for a single IP address.

Bash Command

awk '{ print $1}' test.log | sort | uniq --count

Result

1 87.140.79.41
3 87.140.79.42

Explain

  1. awk '{ print $1}' test.log
87.140.79.42
87.140.79.42
87.140.79.41
87.140.79.42
  1. sort
87.140.79.41
87.140.79.42
87.140.79.42
87.140.79.42
  1. uniq --count [1]
1 87.140.79.41
3 87.140.79.42
  • [1] -c, --count: prefix lines by the number of occurrence
Last edit
Emanuel
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2024-01-23 07:59)