Turn from:Shell Several methods for judging string inclusion relationships
Now every time you analyze the site log, you need to determine whether Baidu Spider is a real spider, after nslookup need to determine if the result contains "Baidu" string
The following is a list of some of the methods that the shell contains to determine the string, the source programmer quiz site StackOverflow and Segmentfault.
Method One: Use grep to find
1 stra= "Long string" 2 strb= "string" 3 result=$ (echo $strA | grep "${STRB}") 4 if [["$result"! = ""]]5 then6 echo "contains" 7 Else8 echo "does not contain" 9 fi
Prints a long string and then grep in a long string to find the string to search for, using the variable result to record the result
If the result is not empty, the description stra contains STRB. If the result is empty, the description is not included.
This method takes full advantage of grep's characteristics and is the most concise.
Method Two: Using the string operator
Stra= "HelloWorld" strb= "Low" if [[$strA =~ $strB]]then echo "contains" Else echo "does not contain" fi
Use the string operator =~ to directly determine whether Stra contains STRB. (This is not more concise than the first method!) )
Method Three: Using wildcard characters
A= "HelloWorld" b= "Low" if [[$A = = * $B *]]then echo "contains" Else echo "does not contain" fi
This is also very easy, with the wildcard * Number Agent stra non-STRB parts, if the results are equal to the description contains, and vice versa.
Method Four: Use case in statement
Thisstring= "1 2 3 4 5" # source string searchstring= "1 2" # search string case $thisString in * "$searchString" *) echo Enemy Spot; *) echo nope;; Esa
This is more complicated, case in I haven't touched yet, but since there's a simpler way
Method Five: Take advantage of replacement
string_a=$1string_b=$2if [[${string_a/${string_b}//} = = $STRING _a]] then # # is not substring. Echo N return 0 Else # is substring. Echo Y return 1 fi
This is complicated, too.
If there are more forms on the StackOverflow, the basic categories are the above.
The shell string contains