Using grep to only get lines with ip addresses

If you need to filter a file to only keep line containing only an ip address on the line, you can use grep with simple regular exception. An IP address is basically a list of exactly 4 numbers separated by dots. I assume here it’s encoded in decimal and each of these numbers thus has 1 to 3 digits:

  • decimal: [0-9] means any character between 0 and 9 (so 0,1,2,3,4,5,6,7,8 or 9).
  • 1 to 3 digits: …{1,3} matches 1 to 3 charactes. Note: we need to escape the curly braces: …\{1,3\}
  • separated by dots: Note: we need to escape the dots: \.
  • containing only an ip address on the line: ^…$ (^ = beginning of line, $ = end of line)

Combining this all gives us the following grep command:

grep '^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$' file.txt

Of course this will also match lines like 400.500.600.700 which is not a valid IP address but I guess the odds are you won’t have such a line in the file.

This is useful when you have some files where you know that when a line contains an IP address it is always at position X. You can then use awk (print $X;) to get this component of the line and remove all lines containing other data with this grep command.

Leave a Reply

Your email address will not be published.