How to check if a string contains a substring in Bash

后端 未结 26 1877
慢半拍i
慢半拍i 2020-11-22 01:58

I have a string in Bash:

string=\"My string\"

How can I test if it contains another string?

if [ $string ?? \'foo\' ]; then         


        
26条回答
  •  醉话见心
    2020-11-22 02:27

    Bash 4+ examples. Note: not using quotes will cause issues when words contain spaces, etc. Always quote in Bash, IMO.

    Here are some examples Bash 4+:

    Example 1, check for 'yes' in string (case insensitive):

        if [[ "${str,,}" == *"yes"* ]] ;then
    

    Example 2, check for 'yes' in string (case insensitive):

        if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then
    

    Example 3, check for 'yes' in string (case sensitive):

         if [[ "${str}" == *"yes"* ]] ;then
    

    Example 4, check for 'yes' in string (case sensitive):

         if [[ "${str}" =~ "yes" ]] ;then
    

    Example 5, exact match (case sensitive):

         if [[ "${str}" == "yes" ]] ;then
    

    Example 6, exact match (case insensitive):

         if [[ "${str,,}" == "yes" ]] ;then
    

    Example 7, exact match:

         if [ "$a" = "$b" ] ;then
    

    Example 8, wildcard match .ext (case insensitive):

         if echo "$a" | egrep -iq "\.(mp[3-4]|txt|css|jpg|png)" ; then
    

    Enjoy.

提交回复
热议问题