How to check if a string contains a substring in Bash

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

    So there are lots of useful solutions to the question - but which is fastest / uses the fewest resources?

    Repeated tests using this frame:

    /usr/bin/time bash -c 'a=two;b=onetwothree; x=100000; while [ $x -gt 0 ]; do TEST ; x=$(($x-1)); done'
    

    Replacing TEST each time:

    [[ $b =~ $a ]]           2.92 user 0.06 system 0:02.99 elapsed 99% CPU
    
    [ "${b/$a//}" = "$b" ]   3.16 user 0.07 system 0:03.25 elapsed 99% CPU
    
    [[ $b == *$a* ]]         1.85 user 0.04 system 0:01.90 elapsed 99% CPU
    
    case $b in *$a):;;esac   1.80 user 0.02 system 0:01.83 elapsed 99% CPU
    
    doContain $a $b          4.27 user 0.11 system 0:04.41 elapsed 99%CPU
    

    (doContain was in F. Houri's answer)

    And for giggles:

    echo $b|grep -q $a       12.68 user 30.86 system 3:42.40 elapsed 19% CPU !ouch!
    

    So the simple substitution option predictably wins whether in an extended test or a case. The case is portable.

    Piping out to 100000 greps is predictably painful! The old rule about using external utilities without need holds true.

    0 讨论(0)
  • 2020-11-22 02:23

    I like sed.

    substr="foo"
    nonsub="$(echo "$string" | sed "s/$substr//")"
    hassub=0 ; [ "$string" != "$nonsub" ] && hassub=1
    

    Edit, Logic:

    • Use sed to remove instance of substring from string

    • If new string differs from old string, substring exists

    0 讨论(0)
  • 2020-11-22 02:27

    I am not sure about using an if statement, but you can get a similar effect with a case statement:

    case "$string" in 
      *foo*)
        # Do stuff
        ;;
    esac
    
    0 讨论(0)
  • 2020-11-22 02:27

    The accepted answer is best, but since there's more than one way to do it, here's another solution:

    if [ "$string" != "${string/foo/}" ]; then
        echo "It's there!"
    fi
    

    ${var/search/replace} is $var with the first instance of search replaced by replace, if it is found (it doesn't change $var). If you try to replace foo by nothing, and the string has changed, then obviously foo was found.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 02:27
    msg="message"
    
    function check {
        echo $msg | egrep [abc] 1> /dev/null
    
        if [ $? -ne 1 ];
        then 
            echo "found" 
        else 
            echo "not found" 
        fi
    }
    
    check
    

    This will find any occurance of a or b or c

    0 讨论(0)
提交回复
热议问题