SoFunction
Updated on 2025-03-09

Summary of the method of judging the relationship between string inclusion using shell

Preface

Now every time you analyze the website log, you need to determine whether Baidu spider is a real spider. After nslookup, you need to determine whether the result contains the "baidu" string.

The following are some methods for determining the string in the shell, from the programmer's Q&A website * and segmentfault.

Method 1: Use grep to find

strA="long string"
strB="string"
result=$(echo $strA | grep "${strB}")
if [[ "$result" != "" ]]
then
  echo "Include"
else
  echo "不Include"
fi

First print a long string, then grep in the long string to find the string to search, and record the result with the variable result

If the result is not empty, strA contains strB. If the result is empty, it means it is not included.

This method makes full use of grep's characteristics and is the simplest.

Method 2: Use string operators

strA="helloworld"
strB="low"
if [[ $strA =~ $strB ]]
then
  echo "Include"
else
  echo "Not included"
fi

Use the string operator =~ to directly determine whether strA contains strB. (Isn't this more concise than the first method?)

Method 3: Use wildcards

A="helloworld"
B="low"
if [[ $A == *$B* ]]
then
  echo "Include"
else
  echo "Not included"
fi

This is also easy. Use wildcard symbol * to proxy the non-strB part of strA. If the results are equal, it means that it contains it, otherwise it does not contain it.

Method 4: Use case in statement

thisString="1 2 3 4 5" # Source stringsearchString="1 2" # Search stringcase $thisString in 
  *"$searchString"*) echo Enemy Spot ;;
  *) echo nope ;;
esa

This is more complicated, I haven't touched on case in yet, but since there is a relatively simple method, why bother

Method 5: Use replacement

STRING_A=$1
STRING_B=$2
if [[ ${STRING_A/${STRING_B}//} == $STRING_A ]]
  then
    ## is not substring.
    echo N
    return 0
  else
    ## is substring.
    echo Y
    return 1
  fi

This is quite complicated, too

Summarize

The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate.