Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  1] [ 0]  / answers: 1 / hits: 1756  / 3 Years ago, mon, november 22, 2021, 4:37:07

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


$ TEST=etchello
$ echo $TEST
etchello

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 etchello.


More From » bash

 Answers
3

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='etchello'

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


[#1692] Monday, November 22, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cugure

Total Points: 188
Total Questions: 110
Total Answers: 103

Location: Dominican Republic
Member since Sun, Sep 4, 2022
2 Years ago
;