1

Please help.

I'm trying to compare string1 against string2 in a Bash script.

I can do the easy bit of:-

if [[ $string1 == $string2 ]]
then    
    yippee    
fi

What I'm having trouble with is the syntax for when

"the$string1" == $string2  or "a$string1" == $string2

or

 $string1 == the$string2 or $string1 == a$string2

I assume it's something like:-

if [[ $string1 == $string2 || "(a|the)$string1" == $string2 || $string1 == "(a|the)$string2" ]]

But it's not and I cannot seem to find the answer. (I'm obviously asking the wrong question!)

Thanks for any help.

PS I'd rather not use any external progs such as awk etc.

JNevill
  • 46,980
  • 4
  • 38
  • 63
John_S
  • 53
  • 2
  • 8
  • 2
    Can you provide some concrete examples of comparisons that should be considered equal and not equal? Do you just want to compare the two strings ignoring any leading `a` or `the`? – chepner Mar 24 '20 at 15:41
  • 1
    Possible duplicates https://stackoverflow.com/questions/19441521/bash-regex-operator https://stackoverflow.com/questions/18709962/regex-matching-in-a-bash-if-statement https://stackoverflow.com/questions/17420994/how-can-i-match-a-string-with-a-regex-in-bash – oguz ismail Mar 24 '20 at 15:46

1 Answers1

0

You might want:

if [[ $string1 == *"$string2"* ]]; then
    echo "string1 contains string2"

elif [[ $string2 == *"$string1"* ]]; then
    echo "string2 contains string1"
fi

Within [[...]] the == operator is a pattern matching operator.

Ref: 6.4 Bash Conditional Expressions


For specifically an optional "a" or "the" prefix:

[[ $string1 == ?(a|the)"$string2" || $string2 == ?(a|the)"$string1" ]]

That uses bash's extended patterns, see 3.5.8.1 Pattern Matching

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Note that the variable on the right-hand side is quoted: that is to treat it as literal text, in case the variable's contents contain shell globbing characters. – glenn jackman Mar 24 '20 at 15:51