W4hf W4hf - 1 year ago 88
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 host1
some other text host1 host1.example.com
123 T

Expected output: host1 host1 host1.example.com

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download