我在Bash中有一个字符串:
string="My string"
如何测试它是否包含另一个字符串?
if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
哪里是我不认识的接线员。我使用echo和grep吗?
if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
这看起来有点笨拙。
我在Bash中有一个字符串:
string="My string"
如何测试它是否包含另一个字符串?
if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
哪里是我不认识的接线员。我使用echo和grep吗?
if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
这看起来有点笨拙。
当前回答
如果使用双括号,也可以在case语句外使用Marcus的答案(*通配符):
string='My long string'
if [[ $string == *"My long"* ]]; then
echo "It's there!"
fi
注意,针字符串中的空格需要放在双引号之间,*通配符应该放在外面。还要注意,使用了简单的比较运算符(即==),而不是正则表达式运算符=~。
其他回答
公认的答案是正确的,但很难阅读和理解。对于与搜索相关的问题,应始终使用$needle in a$haystack习语。由于建议的编辑队列已满,我发布了以下内容:
haystack='There are needles here.'
if [[ "$haystack" == *"needle"* ]]; then
echo "It's there!"
fi
这也适用于:
if printf -- '%s' "$haystack" | egrep -q -- "$needle"
then
printf "Found needle in haystack"
fi
阴性试验为:
if ! printf -- '%s' "$haystack" | egrep -q -- "$needle"
then
echo "Did not find needle in haystack"
fi
我认为这种风格更为经典——更少依赖于Bash shell的特性。
--参数是纯粹的POSIX偏执狂,用于防止类似于选项的输入字符串,例如--abc或-a。
注意:在紧密循环中,此代码将比使用内部Bashshell特性慢得多,因为将创建一个(或两个)单独的进程并通过管道连接。
由于POSIX/BusyBox问题在没有提供正确答案(IMHO)的情况下结束,我将在这里发布答案。
最简单的答案是:
[ ${_string_##*$_substring_*} ] || echo Substring found!
or
[ "${_string_##*$_substring_*}" ] || echo 'Substring found!'
注意,对于某些shell(ash),双哈希是必须的。当未找到子字符串时,上面将计算[stringvalue]。它不会返回错误。找到子字符串时,结果为空,其结果为[]。这将抛出错误代码1,因为字符串被完全替换(由于*)。
最短最常见的语法:
[ -z "${_string_##*$_substring_*}" ] && echo 'Substring found!'
or
[ -n "${_string_##*$_substring_*}" ] || echo 'Substring found!'
另一个:
[ "${_string_##$_substring_}" != "$_string_" ] && echo 'Substring found!'
or
[ "${_string_##$_substring_}" = "$_string_" ] || echo 'Substring found!'
注意单个等号!
通用的大海捞针示例下面是变量
#!/bin/bash
needle="a_needle"
haystack="a_needle another_needle a_third_needle"
if [[ $haystack == *"$needle"* ]]; then
echo "needle found"
else
echo "needle NOT found"
fi
使用jq:
string='My long string'
echo $string | jq -Rr 'select(contains("long"))|"It is there"'
jq中最困难的事情是打印单个引用:
echo $string | jq --arg quote "'" -Rr 'select(contains("long"))|"It\($quote)s there"'
仅使用jq检查条件:
if jq -Re 'select(contains("long"))|halt' <<< $string; then
echo "It's there!"
fi