How to check if a string contains a substring in Bash

后端 未结 26 1926
慢半拍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:17

    I found to need this functionality quite frequently, so I'm using a home-made shell function in my .bashrc like this which allows me to reuse it as often as I need to, with an easy to remember name:

    function stringinstring()
    {
        case "$2" in
           *"$1"*)
              return 0
           ;;
        esac
        return 1
    }
    

    To test if $string1 (say, abc) is contained in $string2 (say, 123abcABC) I just need to run stringinstring "$string1" "$string2" and check for the return value, for example

    stringinstring "$str1" "$str2"  &&  echo YES  ||  echo NO
    

提交回复
热议问题