如果我在 shell 变量中有文本,说 $a
:
a="The cat sat on the mat"
如何使用 Linux shell 脚本搜索“cat”并返回 4,如果未找到则返回 -1?
最佳答案
使用 bash
a="The cat sat on the mat"
b=cat
strindex() {
x="${1%%"$2"*}"
[[ "$x" = "$1" ]] && echo -1 || echo "${#x}"
}
strindex "$a" "$b" # prints 4
strindex "$a" foo # prints -1
strindex "$a" "ca*" # prints -1
关于linux - 使用 Linux shell 脚本在字符串中的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5031764/