Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat a number in string twice using sed command

Let's say I have hell0 w0rld, I want it to become hell00 w0rld. I tried sed s/0/00/, but that only replaces 0, it wouldn't work for he1lo wor1d(he11lo wor1d), what can I do so that it replaces any first digit, instead of just 0?

like image 380
P7GAB Avatar asked Feb 12 '26 21:02

P7GAB


1 Answers

Since you don't want to match just 0, but any digit, you want to use [0-9]. This stands for "any one of the digits 0-9". You put this in parentheses to "capture" it, and in the replacement string, you can add backrefences:

$ sed 's/\([0-9]\)/\1\1/' <<< "he1lo wor1d"
he11lo wor1d

If you want to repeat the first number (as per the title) and not just digit, you append \+ to your character class. This stands for "one or more of these":

$ sed 's/\([0-9]\+\)/\1\1/' <<< "he12o wor1d"
he1212o wor1d

An alternative to the backreferences \1, which match the capture group /(.../), would be to use &, which stands for the complete match, i.e.,

sed 's/[0-9]/&&/' <<< "he1lo wor1d"

and

sed 's/[0-9]\+/&&/' <<< "he12lo wor1d"

where the /(.../) are not needed any longer.

like image 63
Benjamin W. Avatar answered Feb 15 '26 14:02

Benjamin W.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!