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
Question
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
Solution
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
OTHER TIPS
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