【发布时间】:2017-10-20 16:49:19
【问题描述】:
执行./test.sh 12.34 时,grep 应该匹配12.34 而不是12-34。这如何实现?
#!/bin/sh
ip=$1
echo $ip
if netstat | grep ssh | grep $ip; then
netstat | grep ssh | grep $ip
else
echo 'No'
fi
【问题讨论】:
执行./test.sh 12.34 时,grep 应该匹配12.34 而不是12-34。这如何实现?
#!/bin/sh
ip=$1
echo $ip
if netstat | grep ssh | grep $ip; then
netstat | grep ssh | grep $ip
else
echo 'No'
fi
【问题讨论】:
您可以将grep 与-F 选项一起使用:
来自 man grep:
-F, --fixed-strings
Interpret pattern as a set of fixed strings (i.e. force grep to
behave as fgrep).
你的例子:
grep -F "$ip"
【讨论】:
"$ip",否则包含空格或全局字符的模式会导致有趣的惊喜。
grep 使用正则表达式匹配字符串。 . 是正则表达式中的特殊字符,所以需要转义。有一种相当优雅的方法:
export escaped_ip_addr = $(echo $ip_addr | sed "s/\./\\\./g")
这将是你的最终代码:
#!/bin/sh
#test.sh
ip=$1
echo $ip
export escaped_ip = $(echo $ip | sed "s/\./\\\./g")
if netstat | grep ssh | grep $escaped_ip; then
netstat | grep ssh | grep $escaped_ip
else
echo 'No'
fi
【讨论】:
= 周围分配空格。