Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

string - 如何检查字符串是否在Bash中包含子字符串(How to check if a string contains a substring in Bash)

I have a string in Bash:

(我在Bash中有一个字符串:)

string="My string"

How can I test if it contains another string?

(如何测试它是否包含另一个字符串?)

if [ $string ?? 'foo' ]; then
  echo "It's there!"
fi

Where ??

(哪里??)

is my unknown operator.

(是我未知的运算符。)

Do I use echo and grep ?

(我是否使用echo和grep ?)

if echo "$string" | grep 'foo'; then
  echo "It's there!"
fi

That looks a bit clumsy.

(看起来有点笨拙。)

  ask by davidsheldon translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use Marcus's answer (* wildcards) outside a case statement, too, if you use double brackets:

(如果使用双括号,您也可以在案例语句之外使用Marcus的答案(*通配符) :)

string='My long string'
if [[ $string == *"My long"* ]]; then
  echo "It's there!"
fi

Note that spaces in the needle string need to be placed between double quotes, and the * wildcards should be outside.

(请注意,针线中的空格必须放在双引号之间,并且*通配符应位于外部。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...