Backslash Missing in File While Replace the String Content Using Backslash Contain Variable

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

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

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.