简体   繁体   中英

How can I compare two similar strings with a wildcard in bash?

How can I best compare two similar strings in bash?

I want to compare 1.1.1.1:1000 to 1.1.1.1 and find it to be a match.

1.1.1.1:1000 1.1.1.1 MATCH
1.1.1.2:1000 1.1.1.1 NO MATCH

Here's a simple script illustrating the challenge:

#!/bin/sh

IPONE="1.1.1.1:1000"
IPTWO="1.1.1.1"

if  [[ "$IPONE" == "$IPTWO*" ]] ; then
    echo "$IPONE $IPTWO Match"
else
    echo "$IPONE $IPTWO ERROR"
fi

If I understand correctly, you want to compare, for an exact match, the part before the colon. In that case:

if  [[ "${IPONE%%:*}" == "${IPTWO%%:*}" ]] ; then
    echo "$IPONE $IPTWO Match"
else
    echo "$IPONE $IPTWO ERROR"
fi

If you want to use glob-syntax, then you need to use =~ instead of == in your [[ ... ]] , and you can't have the second parameter quoted. So it should like this:

if [[ "$IPONE" =~ $IPTWO* ]]; then

If you need to have the second parameter quoted, just do this:

if [[ "$IPONE" =~ "$IPTWO"* ]]; then

If you need to find a match that matches a string up to the last of a delimiter, in this case . , then try this:

if [[ "$IPONE" =~ ([0-9]|\.){3}[0-1]* ]]; then

I think POSIX substring parameter expansion , may be have trick

#!/bin/bash

IPONE="1.1.1.1:1000"
IPTWO="1.1.1.1"

if test "${IPONE#*$IPTWO}" != "$IPONE"
then
     echo "$IPONE $IPTWO Match"
else
     echo "$IPONE $IPTWO ERROR"
fi

OR

IPONE="1.1.1.1:1000"
IPTWO="1.1.1.1"

if [[ "${IPONE}" == *$IPTWO* ]]
then
     echo "$IPONE $IPTWO Match"
else
     echo "$IPONE $IPTWO ERROR"
fi

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM