Extracting IP Addresses from a Log File with grep and sort

Find ip address in logfile.

* This page contains promotional content

Log files come in all kinds of formats, so you will not necessarily get the same result; treat this as a rough reference only.
This time I extract the IP addresses of my own subnet from a dnsmasq log file

The dnsmasq log

Jan 25 05:45:04 dnsmasq[1]: query[A] firestore.googleapis.com from 192.168.1.43
Jan 25 05:45:04 dnsmasq[1]: cached firestore.googleapis.com is 142.250.196.106
Jan 25 05:45:04 dnsmasq[1]: query[AAAA] firestore.googleapis.com from 192.168.1.43
Jan 25 05:45:04 dnsmasq[1]: cached firestore.googleapis.com is 2404:6800:4004:827::200a
Jan 25 05:45:04 dnsmasq[1]: reply easylist-downloads.adblockplus.org is 65.21.35.75
Jan 25 05:45:04 dnsmasq[1]: reply easylist-downloads.adblockplus.org is 136.243.9.187
Jan 25 05:45:04 dnsmasq[1]: reply easylist-downloads.adblockplus.org is 141.95.40.123
Jan 25 05:45:04 dnsmasq[1]: reply easylist-downloads.adblockplus.org is 51.255.232.90
Jan 25 05:45:04 dnsmasq[1]: reply easylist-downloads.adblockplus.org is 95.216.77.130
Jan 25 05:45:04 dnsmasq[1]: reply easylist-downloads.adblockplus.org is 95.217.32.92
Jan 25 05:45:05 dnsmasq[1]: query[A] firestore.googleapis.com from 192.168.1.43
Jan 25 05:45:05 dnsmasq[1]: cached firestore.googleapis.com is 142.250.196.106
Jan 25 05:45:05 dnsmasq[1]: query[AAAA] firestore.googleapis.com from 192.168.1.43
-

Extracting only the IP addresses

From all of this, extract only the IP addresses in the form 192.168.1.*

$ grep -Eo '192\.168\.1\.[0-9]{1,3}' dnsmasq.log

192.168.1.5
192.168.1.5
192.168.1.60
192.168.1.60
192.168.1.60
192.168.1.60
192.168.1.60
192.168.1.63
192.168.1.63
192.168.1.63
192.168.1.63
192.168.1.63
-

Removing duplicate IP addresses

The same address is shown several times, so remove the duplicates

$ grep -Eo '192\.168\.1\.[0-9]{1,3}' dnsmasq.log | sort -u

192.168.1.153
192.168.1.18
192.168.1.19
192.168.1.233
192.168.1.30
192.168.1.40
192.168.1.43
192.168.1.44
192.168.1.47
192.168.1.49
192.168.1.5
192.168.1.50
-

Formatting it for readability (the final form)

Because it is sorted only by the first digit of the fourth octet, I want to rearrange it into an order that is easy to follow numerically

$ grep -Eo '192\.168\.1\.[0-9]{1,3}' dnsmasq.log | sort -uV

192.168.1.1
192.168.1.5
192.168.1.10
192.168.1.18
192.168.1.19
192.168.1.30
192.168.1.40
-

Saving to a file

Up to here everything goes to standard output, so if you need it, save the result of the command to a file

$ grep -Eo '192\.168\.1\.[0-9]{1,3}' dnsmasq.log | sort -uV -o ip.txt