如果我有一个shellvariables的文本,说$a
:
a="The cat sat on the mat"
如何search“cat”并使用Linux shell脚本返回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
您可以使用grep来获取字符串匹配部分的字节偏移量:
echo $str | grep -b -o str
按照你的例子:
[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat 4:cat
如果你只是想要第一部分,你可以管awk
echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}'
我用这个awk
a="The cat sat on the mat" test="cat" awk -va="$a" -vb="$test" 'BEGIN{print index(a,b)}'
echo $a | grep -bo cat | sed 's/:.*$//'