I have a file something like this

Script blabla
Script bla bla
Script bla bla
Script bla bla

I want to get only the lines that contain just a single ip not all the ips from all the lines.

How can i do this?

the results should be

1 Answer 1


The cat utility just concatenates the data given to it, so it would not be of much use here.

Assuming it's ok to be somewhat sloppy with what constitutes a valid IP address:

grep -Ex '([0-9]{1,3}\.){3}[0-9]{1,3}' file

This would match and print any lines matching the given regular expression (and discard the others).

An even sloppier solution would be to discard lines that contains anything but dots and digits:

grep -v '[^0-9.]' file

Depending on your requirements, one of these would be enough.

For a completely correct regular expression (does not match invalid IP addresses), you could use

grep -Ex '((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])' file
  • none of those work... Jun 13, 2018 at 8:58
  • cat putty.txt | grep -v '[^0-9.]' Binary file (standard input) matches Jun 13, 2018 at 8:59
  • root@localhost:~# grep -Ex '([0-9]{1,3}\.){3}[0-9]{1,3}' putty.txt root@localhost:~# Jun 13, 2018 at 9:03
  • @Killroy2018 I've tested all of these on the data you provided, and they all work. If grep is saying that the file is "binary", then you are not working with a text file, and certainly not the file that you posted.
    – Kusalananda
    Jun 13, 2018 at 9:13
  • sorry mate, you are right, if i test it with my example or similar it works fine. I have to see the particularities of my specific file as i cand give a real sample. It is the saved output from putty, it is text Jun 13, 2018 at 9:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .