Jon
Jon

Reputation: 12992

Filter out IP using regex and sed

I'm having real trouble converting my regular expression into a working sed command on Centos 5.5.

I want to filter the IP address out of a string:

"example.org has address 123.45.67.890" -> "123.45.67.890"

My regular expression so far is:

/([a-zA-Z\. ]+)([0-9\.]+)/

And an example of my command using sed is:

host example.org | grep 'has address' | sed 's/\([a-zA-Z\\. ]+\)\([0-9\\.]+\)/\2/'

But all I get back from that command is the input to sed: "example.org has address 123.45.67.890"

Any ideas?

Upvotes: 1

Views: 6454

Answers (6)

Esteban Santiago
Esteban Santiago

Reputation: 1

host exmaple.org | sed -n 's/^.* (.*)$/\1/p'

Upvotes: 0

Charles Foucault
Charles Foucault

Reputation: 56

host example.org | awk '/has address/ {print $4 }'

Upvotes: 4

Dennis Williamson
Dennis Williamson

Reputation: 360015

Using GNU grep:

host example.org | grep -Po '.*has address \K[0-9.]*'

Upvotes: 0

Justin Morgan
Justin Morgan

Reputation: 30740

Your ([a-zA-Z\. ]+) captures everything before the IP address and includes that in the match. It will also cause matching to fail if the domain name has any numbers in it. Use a lookbehind:

/(?<has address )\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/

You apparently need to use Perl mode for sed to support lookbehinds. You could also use capture groups. If you want a more discriminating pattern (i.e. only match stuff that looks very strongly like an IP address), you can try this:

/(?<has address )(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\b/

That should match four numbers from 0-255, delimited by dots and preceded by 'has address '.

Upvotes: 0

Mark Loeser
Mark Loeser

Reputation: 18627

Here's a very simple way to do it without a regex:

host example.org | grep "has addres" | awk '{print $4}'

Upvotes: 2

Michael Berkowski
Michael Berkowski

Reputation: 270607

You don't really need sed for this. You could use cut instead to parse the spaces:

host example.org | grep 'has address' | cut -d' ' -f4

This just takes the 4th word, when delimited by spaces.

Upvotes: 1

Related Questions