Escape dots in domains names using sed in Bash
I am trying to keep the return of a sed substitution in a v开发者_如何学Pythonariable:
D=domain.com echo $D | sed 's/\./\\./g'
Correctly returns: domain\.com
D1=`echo $D | sed 's/\./\\./g'` echo $D1
Returns: domain.com
What am I doing wrong?
D2=`echo $D | sed 's/\./\\\\./g'` echo $D2
Think of shells rescanning the line each time it is executed. Thus echo $D1, which has the escapes in it, have the escapes applied to the value as the line is parsed, before echo sees it. The solution is yet more escapes.
Getting the escapes correct on nested shell statements can make you live in interesting times.
The backtick operator replaces the escaped backslash by a backslash. You need to escape twice:
D1=`echo $D | sed 's/\./\\\\./g'`
You may also escape the first backslash if you like.
精彩评论