Linux /bin/sh check if string contains X

前端 未结 3 946
终归单人心
终归单人心 2021-01-05 01:36

In a shell script, how can I find out if a string is contained within another string. In bash, I would just use =~, but I am not sure how I can do the same in /bin/sh. Is i

相关标签:
3条回答
  • 2021-01-05 01:37

    You can try lookup 'his' in 'This is a test'

    TEST="This is a test"
    if [ "$TEST" != "${TEST/his/}" ]
    then
    echo "$TEST"
    fi
    
    0 讨论(0)
  • 2021-01-05 01:43

    You can define a function

    matches() {
        input="$1"
        pattern="$2"
        echo "$input" | grep -q "$pattern"
    }
    

    to get regular expression matching. Note: usage is

    if matches input pattern; then
    

    (without the [ ]).

    0 讨论(0)
  • 2021-01-05 01:56

    You can use a case statement:

    case "$myvar" in
    *string*) echo yes ;;
    *       ) echo no ;;
    esac
    

    All you have to do is substitute string for whatever you need.

    For example:

    case "HELLOHELLOHELLO" in
    *HELLO* ) echo "Greetings!" ;;
    esac
    

    Or, to put it another way:

    string="HELLOHELLOHELLO"
    word="HELLO"
    case "$string" in
    *$word*) echo "Match!" ;;
    *      ) echo "No match" ;;
    esac
    

    Of course, you must be aware that $word should not contain magic glob characters unless you intend glob matching.

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