Unexpected substitution for & with sed Unexpected substitution for & with sed shell shell

Unexpected substitution for & with sed


& is a special character meaning "the whole matched string" in the s/// command. Use \&.


Use any character as a command delimiter, here is an example:

sed -Ei "s|$k|$j|g" filename.txt


In addition to the special characters you can also make the commands a bit safer and shorter:

  • There's no need for mv if your sed supports -i (in-place replacement)
  • To avoid setting IFS for the rest of the commands you can limit its scope
  • Escape & in $html

The result:

#!/bin/bashwhile IFS="," read orig htmldo    for fl in *.php    do        sed -i 's/'$orig'/'${html//&/\\&}'/g' "$fl"    donedone < "htm.csv"

Please add an example if it doesn't work for you. There could be other special characters which would have to be escaped.