2

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.

evachristine
  • 2,603
  • 10
  • 39
  • 55

1 Answers1

4

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 ^).

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
cuonglm
  • 150,973
  • 38
  • 327
  • 406