我在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
这看起来有点笨拙。
当前回答
我喜欢sed。
substr="foo"
nonsub="$(echo "$string" | sed "s/$substr//")"
hassub=0 ; [ "$string" != "$nonsub" ] && hassub=1
编辑,逻辑:
使用sed从字符串中删除子字符串的实例如果新字符串与旧字符串不同,则存在子字符串
其他回答
msg="message"
function check {
echo $msg | egrep [abc] 1> /dev/null
if [ $? -ne 1 ];
then
echo "found"
else
echo "not found"
fi
}
check
这将发现a、b或c的任何出现
公认的答案是正确的,但很难阅读和理解。对于与搜索相关的问题,应始终使用$needle in a$haystack习语。由于建议的编辑队列已满,我发布了以下内容:
haystack='There are needles here.'
if [[ "$haystack" == *"needle"* ]]; then
echo "It's there!"
fi
如果您喜欢正则表达式方法:
string='My string';
if [[ $string =~ "My" ]]; 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特性慢得多,因为将创建一个(或两个)单独的进程并通过管道连接。
通用的大海捞针示例下面是变量
#!/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