bash 在bash变量中转义点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15004948/
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
Escaping dots in bash variables
提问by Tim Bellis
I want to escape dots from an IP address in Unix shell scripts (bash or ksh) so that I can match the exact address in a grep command.
我想从 Unix shell 脚本(bash 或 ksh)中的 IP 地址转义点,以便我可以匹配 grep 命令中的确切地址。
echo $ip_addr | sed "s/\./\\./g"
works (outputs 1\.2\.3\.4), but
有效(输出 1\.2\.3\.4),但是
ip_addr_escaped=`echo $ip_addr | sed "s/\./\\./g"`
echo $ip_addr_escaped
Doesn't (outputs 1.2.3.4)
不(输出 1.2.3.4)
How can I correctly escape the address?
如何正确转义地址?
Edit:It looks like
编辑:看起来像
ip_addr_escaped=`echo $ip_addr | sed "s/\./\\\\./g"`
works, but that's clearly awful!
有效,但这显然很糟糕!
回答by chepner
bashparameter expansion supports pattern substitution, which will look (slightly) cleaner and doesn't require a call to sed:
bash参数扩展支持模式替换,它看起来(稍微)更干净并且不需要调用sed:
echo ${ip_addr//./\.}
回答by ruakh
Yeah, processing of backslashes is one of the strange quoting-related behaviors of backticks `...`. Rather than fighting with it, it's better to just use $(...), which the same except that its quoting rules are smarter and more intuitive. So:
是的,反斜杠的处理是反引号的一种奇怪的引用相关行为`...`。与其与之抗争,不如直接使用$(...),除了它的引用规则更智能和更直观之外,它是相同的。所以:
ip_addr_escaped=$(echo $ip_addr | sed "s/\./\\./g")
echo $ip_addr_escaped
But if the above is really your exact code — you have a parameter named ip_addr, and you want to replace .with \.— then you can use Bash's built-in ${parameter/pattern/string} notation:
但是,如果以上确实是您的确切代码——您有一个名为 的参数ip_addr,并且您想替换.为\.——那么您可以使用 Bash 的内置符号:${parameter/pattern/string}
ip_addr_escaped=${ip_addr//./\.}
Or rather:
更确切地说:
grep "${ip_addr//./\.}" [FILE...]
回答by Jonas Berlin
Replace the double quotes with single quotes.
用单引号替换双引号。

