regex - 尽管在正则表达式测试器中匹配,为什么 bash 中的这个正则表达式与该行不匹配?
问题描述
我正在尝试匹配netstat
本地端口与传递给我的脚本的某个端口匹配的行。但是这个正则表达式(虽然它在正则表达式测试器中匹配)似乎不起作用。
# Get lines from netstat
IFS=$'\r\n' GLOBIGNORE='*' command eval 'NetstatLines=($(netstat -anq))'
for line in "${NetstatLines[@]}"; do
# This never matches
if [[ "$line" =~ ^\s*(TCP|UDP)\s+(\d+\.\d+\.\d+\.\d+:$iPort|\[::\d*\]:$iPort)\s+ ]]; then
echo "found it!!"
fi
done
这些行看起来像:
Active Connections
Proto Local Address Foreign Address State
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING
TCP 0.0.0.0:445 0.0.0.0:0 LISTENING
TCP 0.0.0.0:623 0.0.0.0:0 LISTENING
TCP 0.0.0.0:2179 0.0.0.0:0 LISTENING
TCP 0.0.0.0:5040 0.0.0.0:0 LISTENING
TCP 0.0.0.0:7680 0.0.0.0:0 LISTENING
所以 if $iPort
is 135
,它应该匹配第 4 行。
解决方案
感谢@Shawn 和这些网站:
我能够弄清楚:
^[[:space:]]*(TCP|UDP)[[:space:]]+([[:digit:]]+[.][[:digit:]]+[.][[:digit:]]+[.][[:digit:]]+:$iPort|[[]::[[:digit:]]*[]]:$iPort)
这相当于我开始使用的非 posix 版本。