Thứ Hai, 20 tháng 11, 2017

RegEx: Find IP Addresses in a File Using Grep

Here are some regular expressions that will help you to perform a validation and to extract all matched IP addresses from a file.
The following regular expressions match IPv4 addresses.
Matched IP addresses can be extracted from a file using grep command.
In this article you’ll find a regular expressions themselves and an example of how to extract matched IP addresses from a file with the grep command.

Regular Expression to Match IP Addresses

Use the following regular expression to match IPv4 addresses (actually it matches all expressions from 0.0.0.0 to 999.999.999.999).
"([0-9]{1,3}[\.]){3}[0-9]{1,3}"

Grep IP Addresses

Parse a file and print all expressions that match a range between 0.0.0.0 and 999.999.999.999.
$ grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}" file.txt
This regular expression is quite simple but you should understand that not all matches are technically valid IP addresses.
Let’s find only valid IP addresses with the second regular expression.

Match only Valid IPv4 Addresses

Use the following regular expression to find and validate the IPv4 addresses:
"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"

Grep Only Valid IP Addresses

Find and extract only valid IP addresses from a file:
$ grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" file.txt
OptionDescription
-E, –extended-regexpUse extended regular expression
-o, –only-matchingPrint IP addresses only
Omit -o option to print lines that contains IP addresses.

Share This!


Không có nhận xét nào:

Đăng nhận xét