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.

This question already has an answer here:

So these are the original texts:

$ printf 'bbb\nb2b\n'
bbb
b2b

This is what I'm doing

$ printf 'bbb\nb2b\n' | sed 's/^b[0-9]/XXX/g'
bbb
XXXb

And this is the output that I want :D

$ printf 'bbb\nb2b\n' | SOME_SED_MAGIC
bbb
XXX2b

My question: How can I swap the "b2b" to "XXX2b", so I put back the "2" from the sed match? "2" could vary.

share|improve this question

marked as duplicate by Gilles, slm, vonbrand, jasonwryan, casey Mar 18 at 3:07

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer 1

up vote 4 down vote accepted

You can use backreference:

$ printf 'bbb\nb2b\n' | sed 's/^b\([0-9]\)/XXX\1/'
bbb
XXX2b

(BTW, you don't need the g flag since that regex can match only once because of the ^).

share|improve this answer

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