Answers:
您可以使用以下形式${VAR/subs}
,其中VAR
包含较大的字符串,并且
subs
是您要查找的子字符串:
my_string=abc
substring=ab
if [ "${my_string/$substring}" = "$my_string" ] ; then
echo "${substring} is not in ${my_string}"
else
echo "${substring} was found in ${my_string}"
fi
之所以起作用,${VAR/subs}
是因为它等于,$VAR
但第一次subs
删除了字符串,特别是如果$VAR
不包含该单词subs
,则不会对其进行修改。
ab was found in abc
,但是如果我使用,substring=z
我得到了z was found in abc
ab is not in abc
。但是z was found in abc
。这很有趣:D
使用bash 文件名模式(又名“ glob”模式)
substr=ab
[[ abc == *"$substr"* ]] && echo yes || echo no # yes
[[ bcd == *"$substr"* ]] && echo yes || echo no # no
以下两种方法不仅可以在bash中使用,而且可以在任何POSIX兼容环境中使用:
substr=ab
for s in abc bcd; do
if case ${s} in *"${substr}"*) true;; *) false;; esac; then
printf %s\\n "'${s}' contains '${substr}'"
else
printf %s\\n "'${s}' does not contain '${substr}'"
fi
done
substr=ab
for s in abc bcd; do
if printf %s\\n "${s}" | grep -qF "${substr}"; then
printf %s\\n "'${s}' contains '${substr}'"
else
printf %s\\n "'${s}' does not contain '${substr}'"
fi
done
以上两个输出:
'abc' contains 'ab'
'bcd' does not contain 'ab'
前者的优点是不产生单独的grep
进程。
请注意,我使用printf %s\\n "${foo}"
而不是echo "${foo}"
因为如果它包含反斜杠,echo
可能会损坏${foo}
。
xrandr
在变量中存储的监视器名称列表中查找监视器名称的子字符串。+1并欢迎加入1K代表俱乐部:)
这是最便携式的解决方案,即使在旧的Bourne外壳和Korn外壳上也可以使用
#!/bin/bash
case "abcd" in
*$1*) echo "It's a substring" ;;
*) echo "Not a substring" ;;
esac
样品运行:
$ ./case_substr.sh "ab"
It's a substring
$ ./case_substr.sh "whatever"
Not a substring
请注意,您不必专门使用echo
,您可以使用exit 1
和exit 0
来表示成功或失败。
我们还可以做的是创建一个具有特定返回值(匹配时为0,不匹配时为1)的函数(如有必要,可以在大型脚本中使用):
$ ./substring_function.sh
ab is substring
$ cat substring_function.sh
#!/bin/sh
is_substring(){
case "$2" in
*$1*) return 0;;
*) return 1;;
esac
}
main(){
if is_substring "ab" "abcdefg"
then
echo "ab is substring"
fi
}
main $@
$ grep -q 'ab' <<< "abcd" && echo "it's a substring" || echo "not a substring"
it's a substring
这种特殊方法对于中的if-else语句很有用bash
。也大多是便携式的
$ awk '$0~/ab/{print "it is a substring"}' <<< "abcd"
it is a substring
$ python -c 'import sys;sys.stdout.write("it is a substring") if "ab" in sys.stdin.read() else exit(1)' <<< "abcd"
it is a substring
$ ruby -e ' puts "is substring" if ARGV[1].include? ARGV[0]' "ab" "abcdef"
is substring
胸怀[[
和"
:
[[ $a == z* ]] # True if $a starts with an "z" (pattern matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).
[ $a == z* ] # File globbing and word splitting take place.
[ "$a" == "z*" ] # True if $a is equal to z* (literal matching).
因此,就像@glenn_jackman所说的那样,但请注意,如果将整个第二项用双引号引起来,它将把测试切换为文字匹配。
与edwin的答案类似,但具有posix&ksh的改进的可移植性,并且触摸效果比Richard的噪音小:
substring=ab
string=abc
if [ "$string" != "${string%$substring*}" ]; then
echo "$substring IS in $string"
else
echo "$substring is NOT in $string"
fi
string=bcd
if [ "$string" != "${string%$substring*}" ]; then
echo "$string contains $substring"
else
echo "$string does NOT contain $substring"
fi
输出:
abc contains ab
bcd does NOT contain ab
echo
语句的顺序。因为我得到了ab is not in abc