我有以下字符串如何检查是否存在子
msg="bbb. aaa.ccc. bbb.dddd. aaa.eee."
子字符串之间的分隔符是空间。
我要检查,例如,如果"aaa.
“存在。在上面味精它不存在。
我要检查,例如,如果"bbb.
”的存在。在上面的味精中存在。
我尝试使用grep,但grep的用换行可以作为子
之间的分隔符怎么做呢?
我有以下字符串如何检查是否存在子
msg="bbb. aaa.ccc. bbb.dddd. aaa.eee."
子字符串之间的分隔符是空间。
我要检查,例如,如果"aaa.
“存在。在上面味精它不存在。
我要检查,例如,如果"bbb.
”的存在。在上面的味精中存在。
我尝试使用grep,但grep的用换行可以作为子
之间的分隔符怎么做呢?
这可以使用模式匹配在bash中完成。要检查是否
# pass the string, the substring, and the word separator
matches() {
[[ $1 == $2$3* ]] || [[ $1 == *$3$2$3* ]] || [[ $1 == *$3$2 ]]
}
msg="bbb. aaa.ccc. bbb.dddd. aaa.eee."
matches "$msg" "aaa." " " && echo y || echo n
matches "$msg" "bbb." " " && echo y || echo n
n
y
这适用于dash,所以它应该与灰太工作:
str_contains_word() {
sep=${3:-" "}
case "$1" in
"$2$sep"* | *"$sep$2$sep"* | *"$sep$2") return 0;;
*) return 1;;
esac
}
msg="bbb. aaa.ccc. bbb.dddd. aaa.eee."
for substr in aaa. bbb.; do
printf "%s: " "$substr"
if str_contains_word "$msg" "$substr"; then echo yes; else echo no; fi
done
我不知道[tag:ash]在双括号内是否以相同的方式匹配模式。 –
exatelly我正在使用灰和[[]]不支持 – MOHAMED