Summary of the method of judging the inclusion relation of string with shell

Time:2021-4-17

preface

Now every time you analyze the website log, you need to judge whether Baidu spider is a real spider. After NSLOOKUP, you need to judge whether the result contains the “Baidu” string

Here are some methods to determine the inclusion of strings in the shell, from the programmer’s question and answer website stackoverflow and segment fault.

Method 1: using grep to search

strA="long string"
strB="string"
result=$(echo $strA | grep "${strB}")
if [[ "$result" != "" ]]
then
  Echo "contains"
else
  Echo "not included"
fi

First print the long string, then grep finds the string to search in the long string, and records the result with the variable result

If the result is not empty, stra contains STRB. If the result is empty, it does not contain.

This method makes full use of the characteristics of grep and is the most concise.

Method 2: use string operator

strA="helloworld"
strB="low"
if [[ $strA =~ $strB ]]
then
  Echo "contains"
else
  Echo "not included"
fi

Use string operator = ~ to judge whether stra contains STRB directly. (isn’t it simpler than the first method!)

Method 3: using wildcards

A="helloworld"
B="low"
if [[ $A == *$B* ]]
then
  Echo "contains"
else
  Echo "not included"
fi

This is also very easy. Use a wildcard * to represent the non STRB part of stra. If the results are equal, it means that it is included. Otherwise, it is not included.

Method 4: 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. I haven’t come into contact with case in yet, but since there is a relatively simple method, why is it so

Method 5: use substitution


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

It’s complicated, too

summary

The above is the whole content of this article, I hope the content of this article can bring some help to your study or work, if you have any questions, you can leave a message to exchange.

Recommended Today

Rust Study RoadMap

background In recent months, I began to learn rust, and began to write some code with rust. Now, I don’t have a deep understanding of rust, but it’s OK to write some code everyday, and I can learn the next step as needed. In the process of learning, the author also read a lot of […]