0

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?

1
  • I think i found the solution, add \ in x="3 \& 4", then I can obtain the result I wish... Commented Sep 8, 2014 at 4:54

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.