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.
echo $ip_addr | sed "s/\./\\\./g"
works (outputs 1\\.2\\.3\\.4), but
ip_addr_escaped=`echo $ip_addr | sed "s/\./\\\./g"`
echo $ip_addr_escaped
Doesn't (outputs 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!
bash
参数扩展支持模式替换,它看起来(略微)更干净,不需要调用sed
:
echo ${ip_addr//./\\.}
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_escaped=${ip_addr//./\\.}
Or rather:
grep "${ip_addr//./\\.}" [FILE...]
用单引号替换双引号。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.