How to check if a string contains a substring in Bash

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

    Extension of the question answered here How do you tell if a string contains another string in POSIX sh?:

    This solution works with special characters:

    # contains(string, substring)
    #
    # Returns 0 if the specified string contains the specified substring,
    # otherwise returns 1.
    contains() {
        string="$1"
        substring="$2"
    
        if echo "$string" | $(type -p ggrep grep | head -1) -F -- "$substring" >/dev/null; then
            return 0    # $substring is in $string
        else
            return 1    # $substring is not in $string
        fi
    }
    
    contains "abcd" "e" || echo "abcd does not contain e"
    contains "abcd" "ab" && echo "abcd contains ab"
    contains "abcd" "bc" && echo "abcd contains bc"
    contains "abcd" "cd" && echo "abcd contains cd"
    contains "abcd" "abcd" && echo "abcd contains abcd"
    contains "" "" && echo "empty string contains empty string"
    contains "a" "" && echo "a contains empty string"
    contains "" "a" || echo "empty string does not contain a"
    contains "abcd efgh" "cd ef" && echo "abcd efgh contains cd ef"
    contains "abcd efgh" " " && echo "abcd efgh contains a space"
    
    contains "abcd [efg] hij" "[efg]" && echo "abcd [efg] hij contains [efg]"
    contains "abcd [efg] hij" "[effg]" || echo "abcd [efg] hij does not contain [effg]"
    
    contains "abcd *efg* hij" "*efg*" && echo "abcd *efg* hij contains *efg*"
    contains "abcd *efg* hij" "d *efg* h" && echo "abcd *efg* hij contains d *efg* h"
    contains "abcd *efg* hij" "*effg*" || echo "abcd *efg* hij does not contain *effg*"
    

提交回复
热议问题