How to Use grep to Extract IP Addresses from File


Often you may want to use the grep command in Bash to extract IP addresses from a file.

You can use the following basic syntax to do so:

grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' data.txt

This particular example extract all IP addresses from the file named data.txt.

The -o flag specifies that we would like to print only the matching patterns and not the entire line.

This syntax works by using [0-9]\{1,3\}\ to extract any group of numbers that have a length of 1 to 3 and it does this four times with each group (formally known as an “octet”) separated by a period, which matches the format of an IP address.

The following example shows how to use this syntax in practice.

Example: Use grep to Extract IP Addresses from File

Suppose that we have a file named data.txt that contains information about IP addresses for various employees at some company.

We can use the cat command to view the contents of this file:

Each line in the file contains an IP address along with additional information about the employees.

Suppose that we would like to extract only the IP address from each line in the file.

We can use the following syntax to do so:

grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' data.txt

The following screenshot shows how to use this syntax in practice:

grep extract IP address

Notice that this returns only the IP address from each line in the file.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

How to Use grep to Get Line Number of Match
How to Use grep to Extract Last Occurrence in File
How to Use grep to List All Files Containing Specific String

Leave a Reply