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
I used awk for this
a="The cat sat on the mat"
test="cat"
awk -v a="$a" -v b="$test" 'BEGIN{print index(a,b)}'
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}'
echo $a | grep -bo cat | sed 's/:.*$//'
With 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