Programmer
Programmer

Reputation: 439

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

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?

Upvotes: 6

Views: 43652

Answers (4)

panksdmz
panksdmz

Reputation: 461

Since the question asks about how this can be done with SED, there is a less known feature about it that can be very useful here - the delimiters can be whatever you want as long as they are not in your replacement string.

So for the above you could do

sed -i "s|$Var1|$Var2|g" test.csv

..and can replace it with $ or : or anything else you like.

Upvotes: 17

Tom Fenech
Tom Fenech

Reputation: 74695

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.

Upvotes: 8

Vargan
Vargan

Reputation: 1327

& is a special char, hence, you need to use a \ Var2 needs to be specified in this way

Var2="A\&B"

Upvotes: 1

anubhava
anubhava

Reputation: 786146

If you don't want to deal with regex and escaping use awk like this:

Var1='IN123'
Var2='A&B'
awk -v v1="$Var1" -v v2="$Var2" 'BEGIN{FS=OFS=","} $2==v1{$2=v2} 1' test.csv
XYZ,A&B

Upvotes: 4

Related Questions