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

I have a string of the format [0-9]+\.[0-9]+\.[0-9]. I need to extract the first, second, and third numbers separately. As I understand it, capture groups should be capable of this. I should be able to use sed "s/\([0-9]*\)/\1/g to get the first number, sed "s/\([0-9]*\)/\2/g to get the second number, and sed "s/\([0-9]*\)/\3/g to get the third number. In each case, though, I am getting the whole string. Why is this happening?

share|improve this question
3  
Capture groups capture the whole group...not individual elements in the group. You need something like 's/\([0-9]\)\([0-9]\)\([0-9]\).*/\1\2\3/' to capture individual numbers. – Munir Feb 16 at 18:10

We can't give you a full answer without an example of your input but I can tell you that your understanding of capture groups is wrong. You don't use the sequentially, they only refer to the regex on the left hand side of the same substitution operator. If you capture, for example, /(foo)(bar)(baz)/, then foo will be \1, bar will be \2 and baz will be \3. You can't do s/(foo)/\1/; s/(bar)/\2/, because, in the second s/// call, there is only one captured group, so \2 will not be defined.

So, to capture your three groups of digits, you would need to do:

sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)/\1 : \2 : \3/'

Or, the more readable:

sed -E 's/([0-9]*)\.([0-9]*)\.([0-9]*)/\1 : \2 : \3/'
share|improve this answer

example --

echo "123.456.78" |sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)/\1/'
123

$ echo "123.456.78" |sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)/\2/'
456

$ echo "123.456.78" |sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)/\3/'
78

Or, all together:

$ echo "123.456.78" |sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)/\1 : \2 : \3/'
123 : 456 : 78
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.