使用Linux shell脚本在字符串中定位字符串?

如果我在shell变量中有文本,请说$a

a="The cat sat on the mat"

如何搜索“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 -v a="$a" -v b="$test" 'BEGIN{print index(a,b)}'
链接地址: http://www.djcxy.com/p/36199.html

上一篇: Position of a string within a string using Linux shell script?

下一篇: How to find substring inside a string (or how to grep a variable)?