Sed command to replace a string which has a special character "&"

awk, bash, sed, shell

Solution

Unfortunately you have been caught out by the fact that `&` has a special meaning in a sed replacement string. It is a metacharacter that means "the entire pattern that was matched". In order to get a literal ampersand, you will have to escape it:

Var1='IN123'
Var2='A\&B'
sed -i "s/$Var1/$Var2/g" test.csv

The single quotes are necessary to prevent the `\&` from being interpreted as an escape sequence in the assignment. I added them to both variables for symmetry.

Problem

Content of test.csv is: ``` XYZ,IN123 ``` Here is my script: ``` Var1=IN123 Var2=A&B sed -i "s/$Var1/$Var2/g" test.csv ``` This is my simple code to replace the content of test.csv, when the code finds IN123, it will be replaced by A&B. So expected output is: ``` XYZ,A&B ``` But with the above code I am getting: ``` XYZ,AIN123B ``` What am I doing wrong?

Original source

Related problems