How to check if a string contains a substring in Bash

后端 未结 26 1924
慢半拍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.

提交回复
热议问题