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

This question already has an answer here:

So these are the original texts:

$ printf 'bbb\nb2b\n'

This is what I'm doing

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

And this is the output that I want :D

$ printf 'bbb\nb2b\n' | SOME_SED_MAGIC

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 '14 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.

up vote 4 down vote accepted

You can use backreference:

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

(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.