简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM