简体   繁体   中英

exact match a string in a variable with a string in another

I have a sentence which is nothing but a string variable with words separated by spaces .

I have another variable which contains a word . What I wanted is to find exact matching of the word in the variable containing the sentence . I have tried this :

read -p "enter the word to match " STR # STR contains VVDNSG 

#this DUP_SG_NAME_PUBLIC variable contains a string which consists of few words 
DUP_SG_NAME_PUBLIC=$(aws ec2 describe-security-groups \
  --query 'SecurityGroups[*].{GroupName:GroupName}' \
  --output text) 

if [[ $DUP_SG_NAME_PUBLIC =~ $STR ]]
then 
echo "true"
else 
echo "false"
fi

Problem Here I have provided "VVDN" as string but I have to match "VVDNSG" but this code works for both . Even for VVDN and VVDNSG which is understandable .

What I want to do
I want to find exact match that is if given VVDNSG as STR value it should print true or else false even with VVDN and I want that to do the comparison with variables not with literal strings .

I have tried few examples googling most of them either tell you to find match in a file or hardcode the string comparison.

Your STR works as a regex. So, to use it as an exact match, explicitly mark the beginning with ^ and the end with $ :

STR="^VVDN$"

Then the if condition will be true only for exact matches of STR in DUP_SG_NAME_PUBLIC .

Update : Actually, I think what you want is somewhat different - you have a sentence containing words separated by spaces (you didn't mention a termination character) and you want to match one of the words, only if it is an exact match. Let's assume it will be an exact match if it has a space after the word or if it is at the end of the sentence.

In that case, your regex could be:

STR="VVDN($| )"

Is this what you meant?

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