Question

I have the following command in my script. It works fine with one exception; it also matches partial entries. I want the match to be exact.

a=mary jane uger dodo baba
b=mary
c=ma    

if [[ "$a" =~ "$b" ]] && [ -n "$1" ]; then
    echo it matches
else
    echo it does not match
fi

So no matter if in the if statement i use value $b or $c they both match. I want to ensure that the entry is fully match and not partially. So this should work and give exact match.

if [[ "$a" =~ "$b" ]]  

and this should not work partial match

if [[ "$a" =~ "$c" ]]

Can someone help please?

here is my exact code

if [[ "$a" =~ "$b" ]]; then
      echo something     
fi
Was it helpful?

Solution 2

z='\>'
[[ $a =~ $b$z ]] # true
[[ $a =~ $c$z ]] # false

does bash support word boundary regular expressions?

OTHER TIPS

Put a space or end anchor in in the end for regex comparison to make sure there is no partial word match:

a='mary jane uger dodo baba'
b='mary'
c='ma'

# will match
[[ "$a" =~ "$b"( |$) ]]

# won't match
[[ "$a" =~ "$c"( |$) ]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top