Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

cat file contains

 inet addr:192.168.154.102 Bcast:192.168.154.255 Mask:255.255.255.0
 inet addr:127.0.0.1 Mask:255.0.0.0

i am extracting the ipaddress(192.168.154.102 and 127.0.0.1) using sed like this :

sed -ne 's/.*\([0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\).*/\1/p'

but it just gives :

5.255.255.0
5.0.0.0
share|improve this question
    
If you only want to grep certain patterns, why not use awk -F'[: ]' '/inet addr:/{ print $4}' file –  val0x00ff Aug 13 '13 at 12:51
    
ifconfig | sed -n '/inet addr:/s/[^:]\+:(\S\+).*/\1/p' –  damphat Aug 13 '13 at 13:10

4 Answers 4

up vote 1 down vote accepted

Use awk:

$ echo "inet addr:192.168.154.102 Bcast:192.168.154.255 Mask:255.255.255.0" | awk '{ split($2, a, ":"); print a[2] }'
192.168.154.102

If you absolutely must use sed, e.g.:

echo "inet addr:192.168.154.102 Bcast:192.168.154.255 Mask:255.255.255.0" | sed 's#.*addr:\([0-9.]*\).*#\1#g'
192.168.154.102
share|improve this answer
    
is there any way i can get the first occurence using sed –  munish Aug 13 '13 at 12:51
    
Using sed, no, because there is no way to make the * non-greedy. –  lgeorget Aug 13 '13 at 12:56
    
@munish I updated my answer. –  Adrian Frühwirth Aug 13 '13 at 12:56
2  
On a side-note, if you have GNU grep you could also do a grep -oP 'addr:\K[0-9.]+' –  Adrian Frühwirth Aug 13 '13 at 13:02

The problem is that asterisk as a regular expression is as greedy as possible and it matches as soon as possible. This simply means that ".*" will match on the first line "almost everything"

inet addr:192.168.154.102 Bcast:192.168.154.255 Mask:2

and on the second one

inet addr:127.0.0.1 Mask:25

and so it prints what remains and what you got.

In your case, I would try to be more specific like using ":" as a delimiter or some prefix like "addr:" or you can remove all characters but not dots and digits as IPv4 address consists only of them. You can try this command:

tr -cd '[0-9. ]' < YOUR_FILE

You can then continue with processing the output.

share|improve this answer

Use

sed -n '/inet addr:/s/[^:]\+:\(\S\+\).*/\1/p'

Try this from command-line

ifconfig | sed -n '/inet addr:/s/[^:]\+:\(\S\+\).*/\1/p'

Output

192.168.154.102
127.0.0.1
share|improve this answer
    
this is "no grep" version –  damphat Aug 13 '13 at 13:03

If you only want to grep certain patterns, why not use

awk -F'[: ]' '/inet addr:/{ print $4}' file
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.