How to check if a string contains a substring in Bash

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

    grep -q is useful for this purpose.

    The same using awk:

    string="unix-bash 2389"
    character="@"
    printf '%s' "$string" | awk -vc="$character" '{ if (gsub(c, "")) { print "Found" } else { print "Not Found" } }'
    

    Output:

    Not Found

    string="unix-bash 2389"
    character="-"
    printf '%s' "$string" | awk -vc="$character" '{ if (gsub(c, "")) { print "Found" } else { print "Not Found" } }'
    

    Output:

    Found

    Original source: http://unstableme.blogspot.com/2008/06/bash-search-letter-in-string-awk.html

提交回复
热议问题