How to check whether in Bash string contains a substring

In Bash string using one of the most common operation is to determine whether a string contains another string.

In this article, we'll show you several ways to check whether the string contains the substring.

Use Wildcards

The easiest way is to use the asterisk wildcard * package substring, and compared with strings. Wildcard is used to represent zero, one or a plurality of symbol characters.

If the test returns true, the substring contained in the string.

In the following example, we use an if statement and the equality operator (==) to check whether the string STR comprising substring SUB:

#!/bin/bash

STR='GNU/Linux is an operating system'
SUB='Linux'
if [[ "$STR" == *"$SUB"* ]]; then
  echo "It's there."
fi

When the execution of the script will output:

OutputIt's there.

Operators use case

In addition to using the if statement, you can also use the case statement to check whether the string contains another string.

#!/bin/bash

STR='GNU/Linux is an operating system'
SUB='Linux'

case $STR in

  *"$SUB"*)
    echo -n "It's there."
    ;;
esac

Use regular expression operators

Another option specified in the string to determine if there is a sub-string using a regular expression operators = ~. When using this operator, the right string is treated as a regular expression.

* Represents zero or more of any character except newline.

#!/bin/bash

STR='GNU/Linux is an operating system'
SUB='Linux'

if [[ "$STR" =~ .*"$SUB".* ]]; then
  echo "It's there."
fi

The script will echo the following:

OutputIt's there.

Use Grep

Use the grep command can also be used to find other substring.

In the following example, we will string $ STR as input to grep and check whether the string $ SUB found in the input string. This command will return true or false depending on circumstances.

#!/bin/bash

STR='GNU/Linux is an operating system'
SUB='Linux'

if grep -q "$SUB" <<< "$STR"; then
  echo "It's there"
fi

-Q option tells grep to be performed silently, output omitted.

in conclusion

Check if the string contains the substring is one of the most basic and common operations Bash script.

After reading this tutorial, you should have a good understanding of how to test whether a string contains another string. You can also use other commands, such as awk or sed for testing.

Guess you like

Origin www.linuxidc.com/Linux/2019-08/159866.htm