Unexpected substitution for & with sed

14,203

Solution 1

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

Solution 2

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

sed -Ei "s|$k|$j|g" filename.txt
Share:
14,203
Priya
Author by

Priya

Updated on June 18, 2022

Comments

  • Priya
    Priya almost 2 years

    I have a CSV file containing some special characters and their HTML entity names

    ex: htm.csv

    À,À
    Á,Á
    Â,Â
    Ã,Ã
    É,É
    Ê,Ê
    Í,Í
    Ó,Ó
    Ô,Ô
    Õ,Õ
    

    and I have a number of .php files where these special characters are present. I have written a shell script

    #!/bin/bash
    IFS=","
    while read orig html
    do
       for fl in *.php; do
       mv $fl $fl.old
       sed 's/'$orig'/'$html'/g' $fl.old > $fl
       done
    done< "htm.csv"
    

    but the problem is when using the contents of $html, it is printing the contents of $orig instead of "&".