在 Bash 中使用 sed 转义域名中的点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7060714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Escape dots in domains names using sed in Bash
提问by Roger
I am trying to keep the return of a sed substitution in a variable:
我试图将 sed 替换的返回值保留在变量中:
D=domain.com echo $D | sed 's/\./\./g'Correctly returns: domain\.com
D1=`echo $D | sed 's/\./\./g'` echo $D1Returns: domain.com
D=domain.com echo $D | sed 's/\./\./g'正确返回:domain\.com
D1=`echo $D | sed 's/\./\./g'` echo $D1返回:domain.com
What am I doing wrong?
我究竟做错了什么?
回答by Gilbert
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.
想想每次执行时,shell 都会重新扫描该行。因此,包含转义符的 echo $D1 在解析该行时将转义符应用于该值,然后 echo 才能看到它。解决方案是更多的转义。
Getting the escapes correct on nested shell statements can make you live in interesting times.
在嵌套的 shell 语句中获得正确的转义可以让您生活在有趣的时代。
回答by Kerrek SB
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.
如果您愿意,您也可以转义第一个反斜杠。

