I have a string that holds characters as well as numbers, e.g.


and I'd like to replace one and two by a new sequence of characters


while keeping the numbers in between unchanged. However, while the two substrings one and two always remain the same, the sequence of number in between may vary in its length; so, for instance,

one0.000230002two, one1293.02two, or one42two 

may occur. So far, I have only managed to do this replacement for a fixed numbers of digits using sed and regular expressions.

Only occurences of one and two around number as shown above should be replaced. All other occurences must stay the same.

  • Why does the intermediate string matter at all? why can't you just globally replace the old sequences with the new ones ex. sed -e 's/one/three/g' -e 's/two/four/g'? Dec 4, 2019 at 22:54
  • Good point. I forgot to mention that there may be other occurrences of 'one' and 'two' (without numbers) in the same file at variable positions that should not be replaced.
    – user384947
    Dec 5, 2019 at 8:48

2 Answers 2


You could do something like:

sed 's/one\([[:digit:].]*\)two/three\1four/g'

The \(...\) captures was is matched within (here a sequence of 0 or more decimal digits or period) so it can be referred to as \1 in the replacement.


I'd suggest the following sed substitution:

$ s="one0.000230002two, one1293.02two, or one42two "
$ sed -E 's/([^ 0-9]+)([0-9]+(\.[0-9]+)?)([^ 0-9,]+)/three\2four/g' <<<"$s"
three0.000230002four, three1293.02four, or three42four
  • Excellent! Tank you very much.
    – user384947
    Dec 5, 2019 at 8:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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