如何确定字符串是否是另一个字符串的子字符串
How to determine if string is a substring to another string
我正在尝试确定包含许多文件路径的大字符串中是否存在子字符串(文件名)。这是我的代码,它不起作用(打印“不包含”)。我尝试与 =~
进行比较,不同的引号用法。从那似乎没有任何效果。请问我的代码有问题吗?
#!/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
如果您反转字符串,它会起作用:
$ 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
$
表格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...
我正在尝试确定包含许多文件路径的大字符串中是否存在子字符串(文件名)。这是我的代码,它不起作用(打印“不包含”)。我尝试与 =~
进行比较,不同的引号用法。从那似乎没有任何效果。请问我的代码有问题吗?
#!/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
如果您反转字符串,它会起作用:
$ 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
$
表格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...