Backslash missing in file while replace the string content using backslash contain variable

I want to write backslashes in a file, and I try to substitute some text with the value from a variable:

$ TEST=\\etc\\hello
$ echo $TEST
\etc\hello

But the backslash is missing when I tying to replace them using sed -i

$ sed -i "s/target_value/$TEST/" $(pwd)/test.txt
results "etchello" in test.txt

I expect the file to contain \etc\hello.

6

2 Answers

This is sed interpreting the \ in your variable as an escape character. You can escape special characters using printf %q:

sed -i "s/target_value/$(printf %q "$TEST")/" test.txt 

Alternatively, your scenario would have worked if you had defined your variable as:

TEST='\\etc\\hello'

Note the single quotes around the sting, that causes $TEST to contain the literal string.

6

You can use shell parameter substitution to escape the backslashes. Ex.:

$ set -x
+ set -x
$ echo 'foo target_value bar' | sed "s/target_value/${TEST//\\/\\\\}/"
+ echo 'foo target_value bar'
+ sed 's/target_value/\\etc\\hello/'
foo \etc\hello bar

See also:

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like