'How to keep dollar sign within sed in the bash script?

I am trying to find a way to escape the dollar sign within the sed command in a bash script. I have found here tons of answers that say that you need to put four backslashes in a row in order to escape the sign. I have also tried the version with two backslashes, but for some reason, I can't get it to work. Can someone please tell me what I'm doing wrong?

Let's say that you have a file called aaa.txt located in /home/Documents. The file has just only one line of text, which says aaa. I am trying to replace it using this command (please don't tell me that I can reference it in a different way than with line numbers because this is just a reduced example of something else I am doing):

sed -i "1ccd /home/userr/$PARAMETER/$METHOD" "/home/userr/Documents/aaa.txt"

The output that I get is this:

cd /home/userr/\/\

Which is not what I want. I want to have exactly this output, with dollar signs in the string:

cd /home/userr/$PARAMETER/$METHOD

What is the proper form of the string passed to the sed command to achieve this?



Solution 1:[1]

You can escape the dollar sign with a backslash:

sed -i "1ccd /home/userr/\$PARAMETER/\$METHOD" "/home/userr/Documents/aaa.txt"

Documentation here: https://www.gnu.org/software/bash/manual/html_node/Escape-Character.html

Solution 2:[2]

You need to remove the double quotes so sed will not try and expand it. This sed should work without escaping needed.

$ sed -i '1ccd /home/userr/$PARAMETER/$METHOD' /home/userr/Documents/aaa.txt

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ErniBrown
Solution 2 HatLess