You can install ripgrep
on MacOS with: brew install --formula ripgrep
.
A variation (bash) on @Orwellophile 's answer, done out the long way. However, it also does the comparison with string lengths instead of comparing strings. You never know how long a string might be! :-) Hopefully, while clearly longer, this answer will be clearer.
function strpos (){local -r needle="${1:?}" ## Prevents empty stringslocal -r haystack="${2:?}" ## Prevents empty strings## From a copy, attempts to remove characters from the end of a string, greedily.local -r remainingHaystack="${haystack%%"$needle"*}"local -ir remainingHaystackLength="${#remainingHaystack}"## When the needle is not found in haystack, these values will be equal.if (( $remainingHaystackLength == ${#haystack} )); thenecho -n -1return 1fiecho -n $remainingHaystackLength}
If the pattern matches a trailing portion of the expanded value of parameter, thenthe result of the expansion is the value of parameter with theshortest matching pattern (the ‘%’ case) or the longest matchingpattern (the ‘%%’ case) deleted.
Example:
If parameter = "/usr/bin/foo/bin", and word = "/bin"
${parameter%word} ## /usr/bin/foo/bin --> /usr/bin/foo (non-greedy)${parameter%%word} ## /usr/bin/foo/bin --> /usr (greedy)
If parameter is ‘@’ or ‘*’, the pattern removal operation is applied to each positional parameter inturn, and the expansion is the resultant list. If parameter is anarray variable subscripted with ‘@’ or ‘*’, the pattern removaloperation is applied to each member of the array in turn, and theexpansion is the resultant list.
Bash Reference Manual: Shell Expansion
Most simple is -expr index "The cat sat on the mat" cat
it will return 5