How to check if a string contains a substring in Bash

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

    I use this function (one dependency not included but obvious). It passes the tests shown below. If the function returns a value > 0 then the string was found. You could just as easily return 1 or 0 instead.

    function str_instr {
       # Return position of ```str``` within ```string```.
       # >>> str_instr "str" "string"
       # str: String to search for.
       # string: String to search.
       typeset str string x
       # Behavior here is not the same in bash vs ksh unless we escape special characters.
       str="$(str_escape_special_characters "${1}")"
       string="${2}"
       x="${string%%$str*}"
       if [[ "${x}" != "${string}" ]]; then
          echo "${#x} + 1" | bc -l
       else
          echo 0
       fi
    }
    
    function test_str_instr {
       str_instr "(" "'foo@host (dev,web)'" | assert_eq 11
       str_instr ")" "'foo@host (dev,web)'" | assert_eq 19
       str_instr "[" "'foo@host [dev,web]'" | assert_eq 11
       str_instr "]" "'foo@host [dev,web]'" | assert_eq 19
       str_instr "a" "abc" | assert_eq 1
       str_instr "z" "abc" | assert_eq 0
       str_instr "Eggs" "Green Eggs And Ham" | assert_eq 7
       str_instr "a" "" | assert_eq 0
       str_instr "" "" | assert_eq 0
       str_instr " " "Green Eggs" | assert_eq 6
       str_instr " " " Green "  | assert_eq 1
    }
    

提交回复
热议问题