3

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'
3
  • What hex value do you want to use?
    – choroba
    Dec 3, 2015 at 8:36
  • 1
    Is this what you need? echo "01XX1234" | sed 's/XX/AB/' Dec 3, 2015 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 Dec 3, 2015 at 8:40

3 Answers 3

5

sed will only replace the matching substring of a string.

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

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/'
01AF1234
  • \{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")
1
  • I think you meant "01" in the \1 explanation. Dec 3, 2015 at 15:41
3

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

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

1
  • ill try this out, thanks for the quick replies Dec 3, 2015 at 8:42
2

Use the hold space:

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

sed commands:

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .