如果我在shell变量中有文本,请说$a:
a="The cat sat on the mat"
Run Code Online (Sandbox Code Playgroud)
如何使用Linux shell脚本搜索"cat"并返回4,如果找不到则返回-1?
gle*_*man 66
随着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
Run Code Online (Sandbox Code Playgroud)
Cer*_*lla 26
您可以使用grep来获取字符串匹配部分的字节偏移量:
echo $str | grep -b -o str
Run Code Online (Sandbox Code Playgroud)
根据你的例子:
[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat
4:cat
Run Code Online (Sandbox Code Playgroud)
如果你只是想要第一部分,你可以把它传递给awk
echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}'
Run Code Online (Sandbox Code Playgroud)
我用awk这个
a="The cat sat on the mat"
test="cat"
awk -v a="$a" -v b="$test" 'BEGIN{print index(a,b)}'
Run Code Online (Sandbox Code Playgroud)
echo $a | grep -bo cat | sed 's/:.*$//'
Run Code Online (Sandbox Code Playgroud)