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?
\& works for me. For example, I can replace all instances of amp with & by using sed "s/amp/\&/g" . If you're still having problems, you should post a new question with your input string and your code. Yea it does.
When working at the command line or with batch files, you must take one of two actions when you use strings that contain an ampersand. Either you must escape the ampersand by using the caret (^) symbol, or you must enclose the string inside quotation marks.
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.
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.
sed -i -e "s/SUBJECT/${subjects[2]//&/\\&}/g" test.svg
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With