using sed to get IP-address

Hi folks!

I need to get an ip address of a string that has the same apperance in every case. The string looks like this:

$node="node_ip:109.50.89.211; node:j20"

What I want to do is to extract the IP-address from this string using regular expression. Since I havn't worked much with regexp's I dont really know how to tackle this.

However, if one is able to extract ip from the pattern:
[0-9]{1-3 digits}.[0-9]{1-3 digits}.[0-9]{1-3 digits}.[0-9]{1-3 digits}
somehow...

Does any of you know how to do this?

Try out this...

node="node_ip:109.50.89.211; node:j20"

echo $node|awk -F";" '{print $1}'|awk -F":" '{print $2}'

will return the IP.

$ echo '$node="node_ip:109.50.89.211; node:j20"' | perl -pe 's/^.*node_ip:(\d{1,3}(\.\d{1,3}){3});.*$/$1/'  
109.50.89.211

Thanks a lot for a quick reply!

This works really well, and I said that the string looks the same in each cases but thats not entierly true.. for some cases is is changed so that node_ip and node is switched. And then this code prints out j20 instead.

I tried laborating with the sed command instead to get it more dynamic.

sh-3.00$ echo $node | sed 's/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}//'

prints out: node_ip:; node:j20

So I actually got the IP to be excluded from it :slight_smile: now i just need to do it the other way around, remove all that Not matches the regexp. Any ideas on how one can negate this os so?

With sed:

node="node_ip:109.50.89.211; node:j20"

echo "$node"|sed 's/.*:\(.*\);.*/\1/'

Regards

A regular expression can be written lax, potentially matching unexpected data, or can be written strictly, matching only exact data. The key is to know what your data looks like and describe it accurately.

Thanks for reply,

But as i said earlier this does not work if you change order of node_ip and node. i.e string looks like this:
"node:j20; node_ip:109.50.89.211"

So do you have both styles? Any other variations?

cat data4
$node="node_ip:109.50.89.211; node:j20"
$node="node:j21; node_ip:109.50.89.211"

$ cat data4 | perl -pe 's/^.*?:(\d{1,3}(\.\d{1,3}){3}).*$/$1/'
109.50.89.211
109.50.89.211

Yes! Thank you very much, works perfectly.

If you are using bash or ksh93 you can use the builtin extended regular expression capability to get the IP address without calling an external utility.

For example here is an example of how to extract the address from the two sample node strings using ksh93

TMP=file.$$

cat <<EOF > $TMP
node_ip:109.50.89.211; node:j20
node:j21; node_ip:109.50.89.211
EOF

while read str
do
     echo ${str/*([[:print:]]):+({1,3}([[:digit:]]){3}(\.{1,3}([[:digit:]])))*([[:print:]])/\2}
done < $TMP

rm $TMP