2

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
theuniverseisflat
  • 861
  • 2
  • 12
  • 19

2 Answers2

2

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"( |$) ]]
anubhava
  • 761,203
  • 64
  • 569
  • 643
0
z='\>'
[[ $a =~ $b$z ]] # true
[[ $a =~ $c$z ]] # false

does bash support word boundary regular expressions?

Community
  • 1
  • 1
Zombo
  • 1
  • 62
  • 391
  • 407
  • cool this works thanks Steven .. I had to remove the quotes around my variable. Can you tell me what does including the '\>' does if u get a chance? – theuniverseisflat Apr 16 '14 at 23:03