T.Poe
T.Poe

Reputation: 2089

How to determine if string is a substring to another string

I'm trying to determine if a substring (a file name) is present in a large string containing many file paths. This is my code which just doesn't work (prints "Does not contain"). I tried comparing with =~, different quotes usages. Nothing from that seems to work. Do you please see a problem in my code?

#!/bin/bash

text="/path/to/some/file1-2-3.json /another/path/to/file4-5-6.json"
my_file="file1-2-3.json"

if [[ *"$my_file"* == "$text" ]]; then
    echo "Contain"
else
    echo "Does not contain"
fi

Upvotes: 0

Views: 61

Answers (1)

MarcoLucidi
MarcoLucidi

Reputation: 2177

it works if you invert the strings:

$ more script.sh
#!/bin/bash

text="/path/to/some/file1-2-3.json /another/path/to/file4-5-6.json"
my_file="file1-2-3.json"

if [[ "$text" == *"$my_file"* ]]; then
        echo "Contain"
else
        echo "Does not contain"
fi
$ ./script.sh
Contain
$

form man bash:

When the == and != operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below under Pattern Matching...

Upvotes: 1

Related Questions