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\helloBut 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.txtI expect the file to contain \etc\hello.
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.
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 barSee also: