1

I needed to replace all & with #, inside and only inside the <faultstring> ... </faultstring> tag. Additionally, the & in &amp; should not be changed. Sample input:

123&&<faultcode>IBM.Error<faultstring>special character & and one converted &amp;</faultstring></faultcode>&&123

Expected output:

123&&<faultcode>IBM.Error<faultstring>special character # and one converted &amp;</faultstring></faultcode>&&123

The following one works with the boundary but also replaces the &amp; with #amp;

sed -e :1 -e 's@\(<faultstring>.*\)&\(.*</faultstring>\)@\1#\2@;t1'

Also, I'm replacing those patterns inplace with a file.

PS: I created a new question to avoid confusion on my previous thread. If you guys found that this can be merged on the previous thread please do so. I'm just hoping that new thread will attract people to answer quick, and minimize confusion.

1
  • Your question title is confusing. From the body of your question, it looks like you mean “… replace a specified character between two words but only replace if the character doesn’t have a succeeding specified word”. Also, what if & is used in other HTML characters, like &lt;, &gt;, &alpha;, &beta;, etc? Commented Aug 29, 2014 at 15:27

1 Answer 1

2

This worked for me:

sed -e :1 -e 's@\(<faultstring>.*\)&\([^amp;]\)\(.*</faultstring>\)@\1#\2\3@;t1' file

To replace it with &amp; use this:

sed -e :1 -e 's@\(<faultstring>.*\)&\([^amp;]\)\(.*</faultstring>\)@\1\&amp;\2\3@;t1' file
7
  • thanks @chaos! this worked fine! i tried to change the # to &amp; but it ddnt work. i tried to escape the ; with \; but no luck. how can i use &amp; instead of #?
    – kemaro
    Commented Aug 29, 2014 at 6:24
  • oopps. nevermind. i already got it. i changed the \1# to \1\&amp thank you very much!
    – kemaro
    Commented Aug 29, 2014 at 6:30
  • @kemaro see my edit
    – chaos
    Commented Aug 29, 2014 at 6:33
  • @kemaro oops, didnt see you 2nd comment...
    – chaos
    Commented Aug 29, 2014 at 6:33
  • hmm ok so first part is done. i would like to change the character that needs to replace? i cant make ' and " work. i like the following to converted.' to &apos;then " to & quot; then < to &lt; and > to & gt; can you help me @chaos?
    – kemaro
    Commented Aug 29, 2014 at 6:46

You must log in to answer this question.

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