@nir
asked on
linux shell script regex to grab only the ip-address
I am trying to grab only the last 200 IP-Address from a log file in linux the shell script the regex i'm using in script is as below
#!/bin/bash
# Sample log file
LOG_FILE="access.log"
# Extract and print IP addresses from the the log
grep -Po '\b(?:\d{1,3}\.){3}\d{1,3}\b' "$LOG_FILE" | grep -v '[[:alpha:]]' | tail -n 200
The regex is taking the version of the user-agent as ip address and prints that too, output as below
108.0.0.0
178.128.206.135
35.92.47.254
34.219.155.134
35.88.66.155
34.215.21.206
34.254.157.74
112.0.0.0
sample of log
"2023-07-10 01:39:01","Unknown Referrer URL","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",178.128.206.135,sample.site.com/
"2023-07-10 05:09:40","Unknown Referrer URL","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36",35.92.47.254,sample.site.com/
"2023-07-10 05:09:53","Unknown Referrer URL","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36",34.219.155.134,sample.site.com/
"2023-07-10 05:10:26",http://sample.site.com,"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36",35.88.66.155,sample.site.com/
"2023-07-10 05:10:34","Unknown Referrer URL","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36",34.215.21.206,sample.site.com/
"2023-07-10 11:03:50","Unknown Referrer URL","Mozilla/5.0 (compatible; NetcraftSurveyAgent/1.0; +info@netcraft.com)",34.254.157.74,sample.site.com/
"2023-07-10 12:02:23","Unknown Referrer URL","Mozilla/5.0 (Macintosh; Intel Mac OS X 13_3_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",195.138.126.179,sample.site.com/
"2023-07-11 00:17:20","Unknown Referrer URL","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/112.0.5615.121 Safari/537.36",65.154.226.168,sample.site.com/
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.