0

I have the following in input.txt:

EA06\\?\.LFRFLB\\?\..*

I want to know if this pattern match with the following string:

EA06.LFRFLB.SHELLO

Then I coded:

MY_STRING="EA06.LFRFLB.SHELLO"
REGEX=$(cat input.txt) # EA06\\?\.LFRFLB\\?\..*

if [[ "${MY_STRING}" =~ "${REGEX}" ]]; then
  echo "FOUND"
else
 echo "NOT FOUND"
fi

if [[ "${MY_STRING}" =~ EA06\\?\.LFRFLB\\?\..* ]]; then
  echo "FOUND"
else
 echo "NOT FOUND"
fi

Result:

NOT FOUND
FOUND

Whats is going wrong here? Why the first if does not match correctly? What is the best way to solve it?

3
  • Shouldn't there be quotes around the output of cat input.txt? Commented May 29, 2014 at 14:39
  • Why would it, the strings are different ? Commented May 29, 2014 at 14:40
  • 3
    @Jidder My brain is hurting too much today. hehe... I should keep my head out of this sort of shell scripting stuff for a while ;) Commented May 29, 2014 at 14:42

1 Answer 1

6

The problem is that you quoted the variable on the RHS of the binary operator =~ which causes the variable replacement to be treated as literal text and not as a regex. You need to say:

if [[ "${MY_STRING}" =~ ${REGEX} ]]; then

Quoting from the manual:

   An additional binary operator, =~, is available, with the  same  prece‐
   dence  as  ==  and !=.  When it is used, the string to the right of the
   operator is considered  an  extended  regular  expression  and  matched
   accordingly  (as  in  regex(3)).   The  return value is 0 if the string
   matches the pattern, and 1 otherwise.  If  the  regular  expression  is
   syntactically  incorrect,  the conditional expression's return value is
   2.  If the shell option nocasematch is enabled, the match is  performed
   without  regard  to the case of alphabetic characters.  Any part of the
   pattern may be quoted to force it to be  matched  as  a  string.

Note the last line in particular:

Any part of the pattern may be quoted to force it to be matched as a string.

Sign up to request clarification or add additional context in comments.

1 Comment

@JohnDoe Note that the usual advice to always quote parameter expansions does not apply inside [[ ... ]], since different rules apply. In particular, such parameter expansions are not subject to filename generation or word splitting

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.