Translate

Archives

Implementing strstr in Korn Shell

Neither Bash or the Korn Shell 93 (ksh93) provide a C-like strstr builtin. Here is a simple implementation of a strstr function in ksh93. The strstr function finds the first occurrence of s2 in s1. If s2 is an empty string, 0 is returned; if s2 occurs nowhere in s1, 0 is also returned; otherwise the offset to the first character of the first occurrence of s2 is returned. #!/bin/ksh function strstr { typeset s1=”$1″ typeset s2=”$2″ if [[ ${#s2} == 0 ]] then return 0 fi typeset len=${#s1} typeset first=${s1%%${s2}*}x typeset ndx=${#first} if (( ndx > len )) then