0

I have a text file as shown below.

    192.168.10.1
   192.168.45.45
    192.168.255.255
    192.168.0.5
    Random text comes here   8.8.8.8
    224.23.25.12
    225.1.2.3
    226.0.0.0
    227.1.2.6
    227.25.25.26
    228.145.123.45
    229.255.255.255

Random text come here 172.32.255.255
231.25.12.12
232.45.13.45
238.0.0.0
233.1.2.3
234.255.255.255
236.123.123.123
237.153.125.155
235.235.235.255
239.239.239.10
172.21.255.255
172.31.10.10
172.16.32.21
Random text comes here 206.32.14.25

I am using grep command to filter all the public IP addresses. And my output should be like this

8.8.8.8
172.32.255.255
206.32.14.25

My code works perfectly fine if I am not using -o flag. But if I add -o flag to get only the pattern I don't get any output.

CODE

egrep -vo  '172\.1[6-9]([\.][0-9]{1,3}){2}|172\.2[0-9]([\.][0-9]{1,3}){2}|172\.3[01]([\.][0-9]{1,3}){2}|10([\.][0-9]{1,3}){3}|192\.168([\.][0-9]{1,3}){2}|22[456789]([\.][0-9]{1,3}){3}|23[0-9]([\.][0-9]{1,3}){3}' private_ip

Any help with this would be appreciated. Thank you

  • 8.8.8.8 and 206.32.14.25 are not private IP addresses, they are public.. – heemayl Mar 28 '16 at 1:46
  • @heemayl Oh yes! My bad. I am trying to get public IPs. I made necessary changes in the post. Thanks! – Swatesh Pakhare Mar 28 '16 at 1:54
  • It works fine without -o option – Mostafa Ahangarha Mar 28 '16 at 5:28
  • Yes. It works fine without -o option. But, with -o, I don't know what's wrong. – Swatesh Pakhare Mar 28 '16 at 5:37
0

As you current example stands, Using GNU sed:

% sed -nr 's/^#.*\s([^\s]+)$/\1/p' file.txt 
8.8.8.8
172.32.255.255
206.32.14.25

Or grep with PCRE:

% grep -Po '^#.*\s\K[^\s]+$' file.txt
8.8.8.8
172.32.255.255
206.32.14.25
0

If the public IPs are always on a line with the text "Hello I am public IP", you could use awk like this:

awk '/Hello I am public IP/ {print $6}'

The whitespace at the beginning of the line is ignored, so $6 is the sixth whitespace-separated field on those lines.

  • No, its not like that. I just made my text file readable – Swatesh Pakhare Mar 28 '16 at 3:12
  • 1
    Well, don't do that (at least, not without mentioning that you've done that). When you say I have a text file as shown below, then people will assume that you mean what you say and base their answers on that. – cas Mar 28 '16 at 3:16
  • I edited the post. – Swatesh Pakhare Mar 28 '16 at 5:35
  • i suggest you edit it again to show the actual unedited text (or mostly-unedited - edit it only the bare minimum required to protect privacy or anonymity and no more). people here may spot usable patterns in the actual text that are not apparent to you. – cas Mar 28 '16 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.