BASH: Grep Regex ip address

BASH: grep regex ip address


To grep an IP V4 s, with regular expression we need to know, how the IP Adresses work.

IPV4: [0-255].[0-255].[0-255].[0-255]

The regular expression for this is:

^(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])$

to use regular expressions for grep, you have to use grep -E.

Ifconfig-example:

ifconfig  | grep -E "(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])"


To prove, if a ip-adress is valid:

echo <IP Adress>  | grep -E „^(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])$“

Example:

echo „266.3.4.5“ | grep -E „^(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])$“

No Output

echo „236.3.4.5“ | grep -E „^(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])$“

Output:  236.3.4.5

I wrote a little bash-script for checking if an ip address is valid.

#!/bin/bash

echo „please insert ip: “
read ip
if [ `echo $ip | grep -E „^(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])$“` ]
then
echo „$ip is a vaild ip“
else
echo „$ip is not a valid ip“
fi

Download VALID-IP-Script

Ein Kommentar zu “BASH: Grep Regex ip address

  1. why not a function, rather than a script? here’s what a function would look like. _and_ it can be used in scripts!

    gip () { cat ${*:–} | grep -E „^(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])$“; }