How To Find All IP Addresses within a File in Linux with grep
TL;DR
# Get all IPv4 addresses
grep -xE "([0-9]{1,3}\.){3}[0-9]{1,3}" file.txt
# Get only valid IPv4 addresses
grep -xE "((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])" file.txt
# Get IPv4 addresses given first 2 numbers (i.e. 999.998.x.x)
grep -xE "(999\.998)(\.[0-9]{1,3}){2}" file.txt
Let’s figure out how this works.
First, we need a regular expression that can match all IPv4 addresses.
Regular Expression to Match IPs
This regular expression will match all expressions from 0.0.0.0 to 999.999.999.999.
([0-9]{1,3}[\.]){3}[0-9]{1,3}
[0-9] looks for all expressions containing a number 0-9.
{1,3} tells us that the preceding expression needs to occur between 1 and 3 times, inclusive (so we want either 1, 2, or 3 consecutive numbers).
[\.] searches for a literal period.
Together, ([0-9]{1,3}[\.]) can find the first number in the IP address (e.g. 0. or 999.).
{3} tells us that we want exactly three occurrences of the previous expression.
Therefore, the expression ([0-9]{1,3}[\.]){3} will give us the first three numbers in the IP address: 0.0.0. or 999.999.999..
[0-9]{1,3} is a manual addition of the fourth number, completing the IP address.
Match All IPs
Any command below will work to print the entire line containing the IP address. Add the -o flag to print just the IP address.
grep -E "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" file.txt
egrep "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" file.txt
\b is a word boundary. It signifies the beginning or end of a word. In our case, the IP address can either be at the beginning of the line, at the end of the line, or in between non-word characters, such as spaces.
grep -E and egrep refer to “extended” regular expressions, which change the meaning of ?, +, {, |, (, and ). To match for match a literal { using extended regex, we can use [{] instead.
grep -xE "([0-9]{1,3}\.){3}[0-9]{1,3}" file.txt
-x selects only matches that exactly match the whole line. We can remove the \b in this scenario.
Match Only Valid IPs
We can use the expression below with a completely correct regular expression.
grep -xE "((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])" file.txt
Match IPs Knowing Part of the IP
Suppose I know the first number in my IP address is 999.x.x.x.
grep -xE "(999)(\.[0-9]{1,3}){3}" file.txt
What if the first two numbers are 999.998.x.x?
grep -xE "(999\.998)(\.[0-9]{1,3}){2}" file.txt
What if the first three are 999.998.997.x?
grep -xE "999\.998\.997\.[0-9]{1,3}" file.txt