Position of a string within a string using Linux shell script?
If I have the text in a shell variable, say $a
:
a="The cat sat on the mat"
How can I search for "cat" and return 4 using a Linux shell script, or -1 if not found?
用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
You can use grep to get the byte-offset of the matching part of a string:
echo $str | grep -b -o str
As per your example:
[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat
4:cat
you can pipe that to awk if you just want the first part
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/36200.html
上一篇: Bash检查字符串是否不包含其他字符串