我想知道如何在 Mac 上的终端上工作,如何找到字符串中是否存在单词。想象有一个变量“a”包含一个包含单词和空格的字符串,一个变量“b”包含一个单词。我想通过 if 来检查单词“b”是否包含在“a”中,或者包含在“a”的一个单词中。谢谢!
问问题
2732 次
2 回答
4
您可以使用模式匹配==
in [[ ... ]]
:
#!/bin/bash
a='I was wondering how, working on terminal on a Mac, can I find if a word is present inside a string.'
b=Mac
if [[ $a == *$b* ]] ; then
echo Found.
fi
于 2013-03-15T12:23:34.567 回答
0
使用grep
$ a='I was wondering how, working on terminal on a Mac, can I find if a word is present inside a string.'
$ b='Mac'
$ c='xxx'
$ grep -q $b <<< $b
$ echo $?
0
$ grep -q $c <<< $c
$ echo $?
1
从man grep
-q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found
要将其放入 if 语句中,请使用
if grep -q foo <<< $string; then
echo "It's there"
fi
或者,如果您更喜欢正则表达式解决方案:
string='My string';
if [[ $string =~ .*My.* ]]
then
echo "It's there!"
fi
或者,使用案例陈述:
case "$string" in
*My*)
echo match
;;
esac
于 2013-03-15T12:42:27.490 回答