W4hf W4hf - 6 days ago 5
Bash Question

Extract lines starting with IP address from file

In shell scripting language, I have to extract from a given file only lines starting with IP addresses

example fileX contains:

text
10.0.0.1 host1
some other text 10.1.1.2
172.22.0.25 host1 host1.example.com
12.8
123 T
260.1.1.1


Expected output:

10.0.0.1 host1
172.22.0.25 host1 host1.example.com

Answer

Assuming that valid IP addresses' octets range from 0 to 255 (some IP numbers are protected, but I am not addressing those), this code should do what you want:

grep -Eh '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' /folder/file | awk -F'.' '$1 <=255 && $2 <= 255 && $3 <= 255 && $4 <= 255' > /tmp/result

The result is stored on /tmp/result

Comments