43Tesseracts
43Tesseracts

Reputation: 4937

Escaping ampersand within a string variable using sed

I am replacing the text SUBJECT with a value from an array variable like this:

#!/bin/bash

# array of subjects, the ampersand causes a problem.
subjects=("Digital Art" "Digital Photography" "3D Modelling & Animation")

echo $subjects[2] # Subject: 3D Modelling & Animation

sed -i -e "s/SUBJECT/${subjects[2]}/g" test.svg

Instead of replacing the text SUBJECT, the resulting text looks like this:

3D Modelling SUBJECT Animation

How can I include the ampersand as a literal & in sed and also have it echo correctly?

Upvotes: 10

Views: 7855

Answers (4)

Anil Singh
Anil Singh

Reputation: 339

reserved corrector & ampersand problem fix.

here is the example sed -i 's+MY_TOKEN+TEST&+g' test.txt
cat test.txt

TESTMY_TOKEN

to fix the behavior

sed -i 's+MY_TOKEN+TEST\&+g' test.txt

cat text.txt

TEST&

Upvotes: 0

tso
tso

Reputation: 4934

sed -i -e "s/SUBJECT/${subjects[2]//&/\\&}/g" test.svg

Upvotes: 1

Benjamin W.
Benjamin W.

Reputation: 52526

You can escape the & in the parameter expansion:

sed -i -e "s/SUBJECT/${subjects[2]//&/\\&}/g" test.svg

This will expand as follows:

$ echo "${subjects[2]//&/\\&}"
3D Modelling \& Animation

and if there is no &, nothing happens.

Upvotes: 4

anubhava
anubhava

Reputation: 786146

Problem is presence of & in your replacement text. & makes sed place fully matched text in replacement hence SUBJECT appears in output.

You can use this trick:

sed -i "s/SUBJECT/${subjects[2]//&/\\&}/g" test.svg

${subjects[2]//&/\\&} replaces each & with \& in 2nd element of subjects array before invoking sed substitution.

Upvotes: 10

Related Questions