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.

  • If you have perl use it with a negative lookahead regex. If you only want to use sed it gets more complicated.
    – kba
    Feb 17, 2016 at 13:02
  • never tried perl. If you have a soln, please let me know.
    – Mani
    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
    Feb 18, 2016 at 14:40

1 Answer 1


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'

You must log in to answer this question.

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