4

I want to replace a '&' with & Except the following occurance of XML special characters.

"   "
'   '
<   &lt;
>   &gt;
&   &amp;

I tried the method mentioned in Replace specified character between two strings? and Replacing all `&` but not the one in XML entity `&amp;` with `#` with sed in a given XML tag does not seem to work for me.

3
  • If you have perl use it with a negative lookahead regex. If you only want to use sed it gets more complicated.
    – kba
    Commented Feb 17, 2016 at 13:02
  • never tried perl. If you have a soln, please let me know.
    – Mani
    Commented Feb 17, 2016 at 13:35
  • 1
    This feels like it might be an XY Problem. What are you actually trying to accomplish here?
    – Sobrique
    Commented Feb 18, 2016 at 14:40

1 Answer 1

3

Using a perl one-liner:

perl -pe 's/&(?!(quot|apos|lt|gt|amp);)/&amp;/g'

The -p flag makes perl behave like sed (loop over STDIN lines, do things, print to STDOUT), -e tells it to read the command from argument not file.

Regular expression substitution does this:

  • match &
    • not followed by
    • quot or apos ... amp
    • semicolon
  • replace with &amp;
  • for all matches on line.

To use it like sed, e.g.

perl -pe 's/&(?!(quot|apos|lt|gt|amp);)/&amp;/g' < my-file.xml
./myscript.sh | perl -pe 's/&(?!(quot|apos|lt|gt|amp);)/&amp;/g'
0

This site is temporarily in read-only mode and not accepting new answers.

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