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?


ANSWERS:


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

echo $a | grep -bo cat | sed 's/:.*$//'

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}'

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)}'


 MORE:


 ? Position of a string within a string using Linux shell script?
 ? Position of a string within a string using Linux shell script?
 ? KornShell - expr index command not working
 ? Find position of a character in a file and store its position bash
 ? Bash checking if string does not contain other string
 ? Bash checking if string does not contain other string
 ? Bash checking if string does not contain other string
 ? Bash checking if string does not contain other string
 ? Comparison of 2 string variables in shell script
 ? Comparison of 2 string variables in shell script