Translate

Image of XSLT 2.0 and XPath 2.0 Programmer's Reference (Programmer to Programmer)
Image of Advanced Programming in the UNIX Environment, Second Edition (Addison-Wesley Professional Computing Series)
Image of Linux Kernel Development (3rd Edition)
Image of Beginning Google Maps API 3

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
        return 0
    fi
    return $ndx
}

line="The quick brown fox jumped over the bush"

strstr "$line" "jumped"
echo "strstr index is: $?"


In general, when you declare a variable inside a function, the variable becomes local to the function that declares it. In ksh93, the only way to declare a local variable is with the typeset builtin in functions declared with the function keyword. If you assign a value to a variable without having declared it with typeset or do not use the function keyword syntax, the variable has global scope. This is because ksh93 has dynamic scoping.

Comments are closed.