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.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

cat file contains

 inet addr: Bcast: Mask:
 inet addr: Mask:

i am extracting the ipaddress( and 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 :
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
up vote 1 down vote accepted

Use awk:

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

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

echo "inet addr: Bcast: Mask:" | sed 's#.*addr:\([0-9.]*\).*#\1#g'
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
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: Bcast: Mask:2

and on the second one

inet addr: 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


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

Try this from command-line

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

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


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.