bash 匹配 IF 语句中的正则表达式

bash match regexp in IF statement

请帮助我了解问题所在。一直在下面的脚本returns"doesn't match"

while true
do
        PING_OUTPUT="64 bytes from 8.8.8.8: icmp_seq=1 ttl=119 time=35.2 ms"  #`ping -c 1 $PING_HOST |sed -n 2p`
        echo "$PING_OUTPUT"
        if [[ "$PING_OUTPUT" =~ 64\sbytes\sfrom\s8.8.8.8:\sicmp_seq=1\sttl=119\stime=35.2\sms ]]
        then
                echo "Match"
        else
                echo "Doesn't match"
        fi
        read -p "Where to ping?" PING_HOST
done

我尝试了不同格式的正则表达式:

if [[ "$PING_OUTPUT" =~ 64[ ]bytes[ ]from[ ]8.8.8.8:[ ]icmp_seq=1[ ]ttl=119[ ]time=35.2[ ]ms ]]

这次显示语法错误:

./main_script.sh: line 10: syntax error in conditional expression
./main_script.sh: line 10: syntax error near `]bytes['
./main_script.sh: line 10: `    if [[ "$PING_OUTPUT" =~ 64[ ]bytes[ ]from[ ]8.8.8.8:[ ]icmp_seq=1[ ]ttl=119[ ]time=35.2[ ]ms ]]'

看起来 =~ 的右侧没有被解释为正则表达式,但我不明白为什么。

Bash 不支持 \s 因为它使用 POSIX 正则表达式库,这就是您第一次尝试失败的原因。


在 bash 手册中写道:

... Any part of the pattern may be quoted to force the quoted portion to be matched as a string...

所以,只要引用那些空格就可以了。例如:

PING_OUTPUT="64 bytes from 8.8.8.8: icmp_seq=1 ttl=119 time=35.2 ms"  #`ping -c 1 $PING_HOST |sed -n 2p`
if [[ "$PING_OUTPUT" =~ 64" "bytes" "from" "8.8.8.8:" "icmp_seq=1" "ttl=119" "time=35.2" "ms ]]; then
    echo "Match"
else
    echo "Doesn't match"
fi

正如 oguzismail 所说 bash 不支持 \s.

如果您想在 bash 中匹配任何形式的白色 space 使用 [[:space:]].

if [[ "$PING_OUTPUT" =~ 64[[:space:]]bytes[[:space:]]from[[:space:]]8.8.8.8:[[:space:]]icmp_seq=1[[:space:]]ttl=119[[:space:]]time=35.2[[:space:]]ms ]]