Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

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
$echo "foo 65 bar" | sed -n -e 's/.*\([0-9]\+\).*/\1/p'

Why is the output not 65? Shouldn't sed greedily match the [0-9]\+ part? How do I tell sed to match all of 65?

share|improve this question
up vote 12 down vote accepted

The .* is greedy first -- it's matching foo 6. The only reason it stops there is because matching any further would stop the whole pattern from matching, so it leaves the 5 for the ([0-9]+). If you made it ([0-9]*) instead the .* would match the whole line and you'd get nothing in your group. One way around it is to tell the first part not to match numbers:

$ echo "foo 65 bar" | sed -n -e 's/[^0-9]*\([0-9]\+\).*/\1/p'
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.