Unix and Linux network configuration. Multiple network interfaces. Bridged NICs. High-availability network configurations.


Reviews of latest Unix and Linux software. Helpful tips for application support admins. Automating application support.


Disk partitioning, filesystems, directories, and files. Volume management, logical volumes, HA filesystems. Backups and disaster recovery.


Distributed server monitoring. Server performance and capacity planning. Monitoring applications, network status and user activity.

Commands & Shells

Cool Unix shell commands and options. Command-line tools and application. Things every Unix sysadmin needs to know.

Home » Commands & Shells

Grepping for IPs

Submitted by on December 11, 2016 – 5:47 pm

This is a small collection of tools and examples for working with IP addresses and ranges in Bash. This post is not meant to be a complete reference, rather a practical how-to guide.

The basic IP regex looks something like this:

grep -oE "([0-9]{1,3}\.){3}([0-9]{1,3})"

This will match an IP address or something that looks a lot like it. If you want only valid IP addresses, the regex becomes a bit longer:
grep -oE "(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]?)"

You can find more examples here. A very useful utility is cidr2regex – a Python script that will convert CIDR notation to a Python-compatible regex. It will not be the prettiest or most efficient regex, but it will get the job done right. Here’s an example:
# echo "" | cidr2regex

Another helpful utility is grepcidr. To install from source:
cd /tmp ; wget ; tar xvfz grepcidr-2.0.tar.gz ; cd grepcidr-2.0/ ; make && make install ; which grepcidr

# grepcidr -v "" /var/log/secure | grep -vc

The ipcalc is a simple but helpful utility for, say, configuring NICs. Here’s a quick example:
# ipcalc -bmnps

A similar but better tool is sipcalc (yum install sipcalc):
# sipcalc
-[ipv4 :] - 0

Host address            -
Host address (decimal)  - 3232266752
Host address (hex)      - C0A87A00
Network address         -
Network mask            -
Network mask (bits)     - 26
Network mask (hex)      - FFFFFFC0
Broadcast address       -
Cisco wildcard          -
Addresses in network    - 64
Network range           - -
Usable range            - -

Here are a few examples of generating various IP ranges (useful for firewall configurations, blacklists, etc).

Using seq:

# seq -f "192.168.122.%g" 40 43

Using bash brace expansion:
# printf "%s\n" 192.168.122.{40..43}


Print Friendly, PDF & Email

Leave a Reply