shell判断字符串包含关系
我们经常遇到shell中需要判断字符串包含关系的场景
下面整理了常用的几种判断方法,代码范例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| #!/bin/bash STR_CONTAINER="ABCDEFGabcdefg" STR_TEST="Gabcd"
echo "STR_CONTAINER = ${STR_CONTAINER}" echo "STR_TEST = ${STR_TEST}" echo "STR_CONTAINER 是否包含 STR_TEST?"
# grep查找法 function test_based_grep() { echo -e " test_based_grep: \c" result=$(echo $STR_CONTAINER | grep "${STR_TEST}") if [[ "$result" != "" ]]; then echo "包含" else echo "不包含!" fi } # 字符串运算符 function test_based_string_operator() { echo -e " test_based_string_operator: \c" if [[ $STR_CONTAINER =~ $STR_TEST ]]; then echo "包含" else echo "不包含!" fi } # 利用通配符 function test_based_wildcards() { echo -e " test_based_wildcards: \c" if [[ $STR_CONTAINER == *$STR_TEST* ]]; then echo "包含" else echo "不包含!" fi } test_based_grep test_based_string_operator test_based_wildcards
|
1 2 3 4 5 6 7
| STR_CONTAINER = ABCDEFGabcdefg STR_TEST = Gabcd STR_CONTAINER 是否包含 STR_TEST? test_based_grep: 包含 test_based_string_operator: 包含 test_based_wildcards: 包含
|