How to check if a string contains a substring in Bash

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

提交回复
热议问题