Issue
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?
Solution
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.
Answered By - anubhava Answer Checked By - Robin (WPSolving Admin)