Law Hong Theng
Law Hong Theng

Reputation: 3

Shell script replace variable with another variable have content & character by using sed

Here is the example:

v="1 & 2"

x="3 & 4"

echo $v | sed "s/$v/$x/"

3 1 & 2 4 <------result not replaced by 3 & 4

I want to replace 1 & 2 to 3 & 4, but seem the result given not the one I needs. Anyone can help to fix my problem?

Upvotes: 0

Views: 92

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753455

The & in the replacement text is a metacharacter that means 'what was matched on the LHS of the s/// operation'.

You'll need to escape the & with a backslash.

v="1 & 2"
x="3 & 4"
y=$(echo "$x" | sed 's/&/\\\&/g')
echo "$y"
echo "$v" | sed "s/$v/$y/"

Output:

3 \& 4
3 & 4

Upvotes: 0

jaypal singh
jaypal singh

Reputation: 77075

In sed & has a special meaning. It contains the entire match from the substitution part. When your replacement variable is expanded sed sees it as 3 & 4 where & contains 1 & 2. Hence you get 3 1 & 2 4 in the output.

You can escape the & to make it work.

$ v="1 & 2"
$ x="3 \& 4"
$ echo $v | sed "s/$v/$x/"
3 & 4

Upvotes: 1

Related Questions