I would like to replace single escape char \ with double \ using sed However when I use
`echo $regex | sed 's/\\/\\\\/g'`
it returns sed: -e expression #1, char 8: unterminated `s' command is there a solution for this?
I would like to replace single escape char \ with double \ using sed However when I use
`echo $regex | sed 's/\\/\\\\/g'`
it returns sed: -e expression #1, char 8: unterminated `s' command is there a solution for this?
I took the commands in the question and ran like so in BASH
:
#!/bin/bash
regex='This\is a \ test'
echo $regex
echo $regex | sed 's/\\/\\\\/g'
results=$(echo $regex | sed 's/\\/\\\\/g')
echo $results
This gives me the expected result of \\
for every found backslash. In the last two lines, I stored the output into a variable called $results
, which appears to be what was attempted in the question with the backticks.
It seems the backticks are making the escape character get evaluated again before being passed to sed
. To get around that, double up how often they get escaped.
`echo $regex | sed 's/\\\\/\\\\\\\\/g'`
Your original rendition would have worked fine if you had not used backticks.
echo $regex | sed 's/\\/\\\\/g'
And this would have worked fine if you had encapsulated it within $()
instead of backticks (as described in another answer).
As noted in comments, if this is part of a script where you are building a pattern to be used elsewhere, there is likely a weakness in your approach if you need this kind of manipulation.