Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping ampersand within a string variable using sed

Tags:

bash

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?

like image 562
43Tesseracts Avatar asked Jun 05 '17 17:06

43Tesseracts


People also ask

How do you escape ampersand in sed?

\& 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.

How do you exit ampersand in Linux?

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.


3 Answers

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.

like image 55
anubhava Avatar answered Oct 20 '22 13:10

anubhava


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.

like image 43
Benjamin W. Avatar answered Oct 20 '22 15:10

Benjamin W.


sed -i -e "s/SUBJECT/${subjects[2]//&/\\&}/g" test.svg
like image 28
tso Avatar answered Oct 20 '22 14:10

tso