Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

egrep and IP addresses

Status
Not open for further replies.

PSD

Instructor
Apr 25, 2000
392
GB
Hi there,

This is giving me a bit of headache. Trying to grep out IP addresses from files, so looking for a "xxx.xxx.xxx.xxx" address format:-

cat /tmp/test |egrep "[0-9]{1,3}\.[0-9]{1,3}\.([0-9]{1,3}"

This is the command I came up with, sort 0-9, 1-3 times followed by a dot. It works but it also picks up numbers which are four characters in length:

1.111.11.1111
111.1111.111.111
111.111.1111.111
111.111.111.1111
1111.111.111.111

Can anyone spot my mistake, it is driving me round the bend and I have a mental block right now!!

Thank you

PSD
IBM Certified Specialist - AIX V4.3 Systems Support
IBM Certified Specialist - AIX V4 HACMP
 
Hi

Let us color them abit so you can see what is matched :
Code:
egrep "[red][0-9]{1,3}[/red]\.[green][0-9]{1,3}[/green]\.[blue][0-9][/blue]{1,3}"

[red]1[/red].[green]111[/green].[blue]11[/blue].1111
111.1[red]111[/red].[green]111[/green].[blue]111[/blue]
[red]111[/red].[green]111[/green].[blue]111[/blue]1.111
[red]111[/red].[green]111[/green].[blue]111[/blue].1111
1[red]111[/red].[green]111[/green].[blue]111[/blue].111
So specify all 4 groups and use -x ( --line-regexp ) :
Code:
egrep -x "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" /tmp/test
Or specify the anchors "manually" :
Code:
egrep "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" /tmp/test
And please avoid the UUOC.

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top