0

I get all the IP address connected to the network along with strings and name of the network, but I wanted to extract only the IP's using awk regex

I tried :

awk '{match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/); ip = substr($0,RSTART,RLENGTH); print ip}'

But it prints IP address along with some numbers and date, say

2019-12-13 12
192.168.1.1
123.168.1.12
0.00012

But I want just the IP address.

oguz ismail
  • 1
  • 16
  • 47
  • 69
Jamuna
  • 21
  • 5

4 Answers4

3

Could you please try following. Since no samples given so didn't test it.

awk 'match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/){print substr($0,RSTART,RLENGTH)}' Input_file

Why OP's code is not working: Since OP has mentioned . in regex which is matching any character NOT literal character . that's why OP is getting results which are NOT IPs too. In above code it is escaped by doing \. which will let awk know to look for literal character . NOT for any character.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
1

In terms of regex, the PCRE-compatible expression (?:[12]?\d{1,2}\.){3}[12]?\d{1,2} should meet your needs. It's a simplified version of the more comprehensive IP regexes that can be found as answers on this question, and can be tested with this demo.

Unfortunately, awk is quite limited in its ability, and is not PCRE compatible. I would suggest using perl instead, but if you're insistent on using awk, the following command should work:

awk 'match($0, /[12]?[0-9]?[0-9]\.[12]?[0-9]?[0-9]\.[12]?[0-9]?[0-9]\.[12]?[0-9]?[0-9]/) {print substr($0, RSTART, RLENGTH)}'

This uses awk-compatible regex to match IPs, and is an expanded form of the above regex. It matches and prints out only the IPs it finds, omitting the rest of the line.


Before you edited your question, your original regex was 0-9]+.[0-9]+.[0-9]+.[0-9]+ - the . allowed it to match any character, meaning hyphens, spaces, and numbers were all valid matches. By specifying \. instead, the regex will exactly match the period character.

oguz ismail
  • 1
  • 16
  • 47
  • 69
Nick Reed
  • 4,989
  • 4
  • 17
  • 37
1

to be honest, I don't have any idea about awk command, but as a good regularexp writer, to extract ip addresses , you can use this optimized exp:

/^([0-9]{0,3}\.){3}[0-9]{1,3}$/g

you can check it here : IP address Regex test

sohaieb azaiez
  • 768
  • 9
  • 20
0

Something like this ?

$ cat file
172.27.1.256 # invalid ip
2019-12-13 12
192.168.1.1
123.168.1.12
0.00012
299.288.299.333 # invalid ip

$ grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5]))\s+?$' file
192.168.1.1
123.168.1.12
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36