How to replace values in a string using sed but keep the string intact?

For example echo "01XX1234"

I'm looking to replace XX with a hex value and leave the 01 and the 1234 intact. I've tried every combination I can think of but sed is getting the better of me.

I can do it like this but is there an easier way?

echo "01XX1234" | sed -n 's/\(01..1234\)/01AB1234/g'
  • What hex value do you want to use? – choroba Dec 3 '15 at 8:36
  • 1
    Is this what you need? echo "01XX1234" | sed 's/XX/AB/' – Nicola Sarobba Dec 3 '15 at 8:39
  • for the example it doesn't matter, im writing a script thst takes a hed value for a specific object in a text file, rather than reference that file manually the manually editing another file accordingly in simply trying to understand sed so i can build a script for my purpose – Kristal Luna Dec 3 '15 at 8:40

sed will only replace the matching substring of a string.

$ echo '01XX1234' | sed 's/XX/AF/'

If you intent to always replace the third and forth character but keep the first and second intact you can use:

$ echo '01XX1234' | sed 's/\(.\{2\}\).\{2\}/\1AF/'
  • \{2\} means two occurrences of the character standing before (in this case .: any character)
  • \(...\) parentheses are used to create a matching group; you can refer to the matched substring later in the pattern or in the replacement string
  • \1 refers to the first matched substring (in this case i.e. "01")
  • I think you meant "01" in the \1 explanation. – Nicola Sarobba Dec 3 '15 at 15:41

echo "01XX1234" | sed 's/XX/AB/'

echo "01XX1234" | sed 's/\(01\).*\(1234\)/\1AB\2/'

  • ill try this out, thanks for the quick replies – Kristal Luna Dec 3 '15 at 8:42

Use the hold space:

> echo "01XX1234" | sed -n 'h;s/01..1234/01AB1234/g;p;x;p'

sed commands:

  • h --> move pattern space to hold space
  • p --> print
  • x --> swap hold space and pattern space

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.