I have a text file as shown below.
    Random text comes here

Random text come here
Random text comes here

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

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.


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

  • and 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

As you current example stands, Using GNU sed:

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

Or grep with PCRE:

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

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.