• Uncategorized

About bash : Escaping-ampersand-within-a-string-variable-using-sed

Question Detail

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?

Question Answer

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

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.